Skip to content

Instantly share code, notes, and snippets.

@parzibyte
Created July 29, 2019 22:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save parzibyte/eab965096e94bcf86920d8ad2fda004f to your computer and use it in GitHub Desktop.
Save parzibyte/eab965096e94bcf86920d8ad2fda004f to your computer and use it in GitHub Desktop.
/*
Algoritmo que convierte un número hexadecimal
a uno decimal en C
@author parzibyte
Visita: parzibyte.me
*/
#include <stdio.h> // printf y fgets
#include <string.h> // strlen
#include <ctype.h> // toupper y isdigit
#include <math.h> // pow
#define LONGITUD_MAXIMA 1000
#define BASE 16
// Prototipos de funciones
unsigned long long hexadecimalADecimal(char *cadenaHexadecimal, int longitud);
int caracterHexadecimalADecimal(char caracter);
int main() {
// Esta primera parte tiene que ver con leer la entrada del usuario,
// únicamente para demostrar
char hexadecimal[LONGITUD_MAXIMA];
printf("Introduce un número hexadecimal de hasta %d caracteres:\n",
LONGITUD_MAXIMA - 1);
fgets(hexadecimal, LONGITUD_MAXIMA, stdin);
hexadecimal[strcspn(hexadecimal, "\r\n")] = 0;
// Ahora sí aquí convertimos
unsigned long long decimal =
hexadecimalADecimal(hexadecimal, strlen(hexadecimal));
printf("El hexadecimal %s es %llu en decimal", hexadecimal, decimal);
return 0;
}
int caracterHexadecimalADecimal(char caracter) {
if (isdigit(caracter))
return caracter - '0';
return 10 + (toupper(caracter) - 'A');
}
unsigned long long hexadecimalADecimal(char *cadenaHexadecimal, int longitud) {
unsigned long long decimal = 0;
int potencia = 0;
for (int i = longitud - 1; i >= 0; i--) {
// Obtener el decimal, por ejemplo para A es 10, para F 15 y para 9 es 9
int valorActual = caracterHexadecimalADecimal(cadenaHexadecimal[i]);
// Elevar 16 a la potencia que se va incrementando, y multiplicarla por el
// valor
unsigned long long elevado = pow(BASE, potencia) * valorActual;
// Agregar al número
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