/* The C Programming Language
my answer to exercise 2-3
Convert a hexadecimal string to an integer.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
int htoi(char h[]);
int main(int argc, char* argv[])
{
char hex[] = "0xDEAD";
printf("%s in hex is equivalent to %d",
hex, htoi(hex) );
return 0;
}
/* Accepts a string of hexadecimal characters
and returns its equivalent integral value. */
int htoi(char h[])
{
int dec, n, i;
dec = n = 0;
for (i = strlen(h)-1; i >= 0; --i, ++n)
if (h[i] == '0')
continue;
else if (h[i] >= '0' && h[i] <= '9')
dec += (h[i] - '0') * pow(16,n);
else if(h[i] >= 'A' && h[i] <= 'F')
dec += (h[i] - 'A' + 10) * pow(16,n);
else
if(i == 1 && h[i] == 'x' && h[i-1] == '0')
return dec;
else
return 0;
return dec;
}