xtoi (Hex to Integer) C function
C language has many functions for converting numerical values to and from string. Here are some from the standard C library:
atof converts a string to a double
atol converts a string to a long
atoi converts a string to an integer
Then you can get the reverse by using sprintf function to get the string representation of numerical values using various formating. That's great for ready made stuffs, though the C library is lacking some functions to convert to and from a hexadecimal string function, we can simply write our own. Here's something I wrote to convert hexadecimal string to integer, I called it xtoi to follow the same function naming used by C library:
// Converts a hexadecimal string to integer
int xtoi(const char* xs, unsigned int* result)
{
size_t szlen = strlen(xs);
int i, xv, fact;
if (szlen > 0)
{
// Converting more than 32bit hexadecimal value?
if (szlen>8) return 2; // exit
// Begin conversion here
*result = 0;
fact = 1;
// Run until no more character to convert
for(i=szlen-1; i>=0 ;i--)
{
if (isxdigit(*(xs+i)))
{
if (*(xs+i)>=97)
{
xv = ( *(xs+i) - 97) + 10;
}
else if ( *(xs+i) >= 65)
{
xv = (*(xs+i) - 65) + 10;
}
else
{
xv = *(xs+i) - 48;
}
*result += (xv * fact);
fact *= 16;
}
else
{
// Conversion was abnormally terminated
// by non hexadecimal digit, hence
// returning only the converted with
// an error value 4 (illegal hex character)
return 4;
}
}
}
// Nothing to convert
return 1;
}
The function above is a little different, as it return the result back to the parameter, hence you need to provide storage to where to put the result, while capturing what the function may return as the conversion status.
xtoi conversion status:
0 - Conversion is successful
1 - String is empty
2 - String has more than 8 bytes
4 - Conversion is in process but abnormally terminated by
illegal hexadecimal character
Sample usage:
unsigned int result;
if (xtoi("ABCD", &result) == 0)
{
printf("ABCD = %d", result);
}
Output:
ABCD = 43981
That's for this time, and next time I will see what I can come up for a function that will convert a 64bit hexadecimal string to its 64bit numerical value.
For now, enjoy and hopefully you may find the function useful.
Edit:
From the comment below the page, you can see the C way of decoding hex from string using sscanf function:
unsigned int hex = 0;
const char* hexstr = "ABCD";
sscanf(hexstr, "%X", &hex);
printf("%s = %d\n", hexstr, hex);