Skip to content

Instantly share code, notes, and snippets.

@parzibyte
Created February 25, 2020 20:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save parzibyte/23e677855469685e2ffb974d68510875 to your computer and use it in GitHub Desktop.
Save parzibyte/23e677855469685e2ffb974d68510875 to your computer and use it in GitHub Desktop.
/*
____ _____ _ _ _
| _ \ | __ \ (_) | | |
| |_) |_ _ | |__) |_ _ _ __ _____| |__ _ _| |_ ___
| _ <| | | | | ___/ _` | '__|_ / | '_ \| | | | __/ _ \
| |_) | |_| | | | | (_| | | / /| | |_) | |_| | || __/
|____/ \__, | |_| \__,_|_| /___|_|_.__/ \__, |\__\___|
__/ | __/ |
|___/ |___/
Blog: https://parzibyte.me/blog
Ayuda: https://parzibyte.me/blog/contrataciones-ayuda/
Contacto: https://parzibyte.me/blog/contacto/
Copyright (c) 2020 Luis Cabrera Benito
Licenciado bajo la licencia MIT
El texto de arriba debe ser incluido en cualquier redistribucion
*/
public class Main {
public static void main(String[] args) {
String hexadecimal = "AB";
long decimal = Integer.parseInt(hexadecimal, 16);
System.out.printf("El hexadecimal %s es %d en hexadecimal usando Integer.parseInt\n", hexadecimal, decimal);
decimal = hexadecimalADecimal(hexadecimal);
System.out.printf("El hexadecimal %s es %d en hexadecimal usando forma propia\n", hexadecimal, decimal);
}
public static int caracterHexadecimalADecimal(char caracter) {
switch (caracter) {
case 'A':
return 10;
case 'B':
return 11;
case 'C':
return 12;
case 'D':
return 13;
case 'E':
return 14;
case 'F':
return 15;
default:
return Integer.parseInt(String.valueOf(caracter));
}
}
public static long hexadecimalADecimal(String hexadecimal) {
long decimal = 0;
// Saber en cuál posición de la cadena (de izquierda a derecha) vamos
int potencia = 0;
// Recorrer la cadena de derecha a izquierda
for (int x = hexadecimal.length() - 1; x >= 0; x--) {
int valor = caracterHexadecimalADecimal(hexadecimal.charAt(x));
long elevado = (long) Math.pow(16, potencia) * valor;
decimal += elevado;
// Avanzar en la potencia
potencia++;
}
return decimal;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment