/* Exercise 2.3 from "The C programming language" book by K&R */
#include <stdio.h>
/* htoi() converts string of hex numbers to decimal value */
int htoi(char str[])
{
int r = 0;
int i;
for (i = 0; (str[2*i] != '\0') && (str[2*i+1]) != '\0'; i++) {
if (str[2*i] == '0' && (str[2*i+1] == 'x' || str[2*i+1] == 'X'))
continue;
r <<= 4;
if (str[2*i] >= 'A' && str[2*i] <= 'F')
r |= str[2*i] - '7';
else if (str[2*i] >= 'a' && str[2*i] <= 'f')
r |= str[2*i] - 'W';
else
r |= str[2*i] - '0';
r <<= 4;
if (str[2*i+1] >= 'A' && str[2*i+1] <= 'F')
r |= str[2*i+1] - '7';
else if (str[2*i+1] >= 'a' && str[2*i+1] <= 'f')
r |= str[2*i+1] - 'W';
else
r |= str[2*i+1] - '0';
}
return r;
}
int main(void)
{
char str1[] = "1abc";
char str2[] = "0x1a0xbc";
char str3[] = "1a0xbC";
printf("%d\n", htoi(str1));
printf("%d\n", htoi(str2));
printf("%d\n", htoi(str3));
return 0;
}
----------