Blob


1 /*
2 * 2-3. Write the function htoi(s), which converts a string of hexadecimal
3 * digits (including an optional 0x or 0X) into its equivalent integer
4 * value. The allowable digits are 0 through 9, a through f, and A through F.
5 */
6 #include <stdio.h>
8 unsigned int htoi(const char s[]);
10 main () {
11 printf("0 %u\n", htoi("0x00000000"));
12 printf("1 %u\n", htoi("0x00000001"));
13 printf("273 %u\n", htoi("0x00000111"));
14 printf("2730 %u\n", htoi("0x00000aaA"));
15 printf("2872373078 %u\n", htoi("0xab34ef56"));
16 printf("4291686144 %u\n", htoi("0XFFcDeF00"));
17 printf("4294967295 %u\n", htoi("0XfffFFFff"));
18 printf("2687823702 %u\n", htoi("a034eF56"));
19 printf("4294967295 %u\n", htoi("fffFFFff"));
20 }
22 unsigned int htoi(const char s[]) {
23 int i = 0;
24 int val = 0;
25 if (s[0] == '0' && (s[1] == 'x' || s[1] == 'X')) {
26 i = 2;
27 }
28 for (; s[i] != '\0'; ++i) {
29 if (s[i] >= '0' && s[i] <= '9') {
30 val = 16*val + s[i] - '0';
31 } else if (s[i] >= 'a' && s[i] <= 'f') {
32 val = 16*val + s[i] - 'a' + 10;
33 } else if (s[i] >= 'A' && s[i] <= 'F') {
34 val = 16*val + s[i] - 'A' + 10;
35 }
36 }
37 return val;
38 }