Skip to content

Instantly share code, notes, and snippets.

@kruttaras
Created March 5, 2017 11:34
Show Gist options
  • Select an option

  • Save kruttaras/0ede2f125ba3cd4e1f9b7ed0783f197f to your computer and use it in GitHub Desktop.

Select an option

Save kruttaras/0ede2f125ba3cd4e1f9b7ed0783f197f to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
int to_hex(char* hex, int i)
{
int size = (int)strlen(hex);
int dec_part;
int val = hex[size - i - 1 ];
if(val >= '0' && val <= '9' )
{
dec_part = (val - 48) * (int)pow(16,i);
} else if(val >= 'A' && val <= 'F' )
{
dec_part = (val- 55) * (int)pow(16,i);
} else if(val >= 'a' && val <= 'f' )
{
dec_part = (val- 87) * (int)pow(16,i);
} else {
exit(1);
}
return i == (size - 1) ? dec_part : dec_part + to_hex(hex, i+1);
}
int hex_to_dec(char hex[])
{
return to_hex(hex, 0);
}
int main() {
char buf[6] = {'3','F','A','0','0','7'};
printf("hex %s = dec %d \n", buf, hex_to_dec(buf) );
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment