|
3 | 3 | * hexadecimal digits (including an optional 0x or 0X) into its equivalent
|
4 | 4 | * integer value. The allowable digits are 0 through 9, a through f, and A
|
5 | 5 | * through F.
|
| 6 | + * |
6 | 7 | * By Faisal Saadatmand
|
7 | 8 | */
|
8 | 9 |
|
9 | 10 | #include <stdio.h>
|
| 11 | +#include <ctype.h> |
10 | 12 |
|
11 |
| -#define MAXCHAR 100 |
| 13 | +#define MAXLEN 1000 |
12 | 14 |
|
13 | 15 | /* functions */
|
14 | 16 | int htoi(char []);
|
15 | 17 |
|
16 | 18 | int htoi(char s[])
|
17 | 19 | {
|
18 |
| - int i, isValid, hexDigit, intValue; |
| 20 | + int i, hexDigit, intValue; |
19 | 21 |
|
| 22 | + /* detect optional 0x or 0X prefix */ |
20 | 23 | i = 0;
|
21 |
| - if (s[i] == '0') { |
22 |
| - ++i; |
23 |
| - if (s[i] == 'x' || s[i] == 'X') |
24 |
| - ++i; |
| 24 | + if (s[0] == '0' && tolower(s[1]) == 'x' && s[2] != '\0') |
| 25 | + i = 2; |
| 26 | + |
| 27 | + hexDigit = intValue = 0; |
| 28 | + for ( ; s[i] != '\0'; ++i) { |
| 29 | + if (!isdigit(s[i]) && (tolower(s[i]) < 'a' || tolower(s[i]) > 'f')) |
| 30 | + return -1; /* invalid input, exit early */ |
| 31 | + if (isdigit(s[i])) |
| 32 | + hexDigit = s[i] - '0'; /* convert digits to hexadecimal*/ |
| 33 | + else |
| 34 | + hexDigit = tolower(s[i]) - 'a' + 10; /* convert letters hexadecimal */ |
| 35 | + intValue = 16 * intValue + hexDigit; /* convert hexadecimal to decimal*/ |
25 | 36 | }
|
26 | 37 |
|
27 |
| - intValue = 0; |
28 |
| - isValid = 1; |
29 |
| - |
30 |
| - for ( ; isValid; ++i) { |
31 |
| - if (s[i] >= '0' && s[i] <= '9') |
32 |
| - hexDigit = s[i] - '0'; |
33 |
| - else if (s[i] >= 'a' && s[i] <= 'f') |
34 |
| - hexDigit = s[i] - 'a' + 10; |
35 |
| - else if (s[i] >= 'A' && s[i] <= 'F') |
36 |
| - hexDigit = s[i] - 'A' + 10; |
37 |
| - else |
38 |
| - isValid = 0; |
39 |
| - |
40 |
| - if (isValid) |
41 |
| - intValue = 16 * intValue + hexDigit; |
42 |
| - } |
43 | 38 | return intValue;
|
44 | 39 | }
|
45 | 40 |
|
46 | 41 | int main(void)
|
47 | 42 | {
|
48 |
| - int value; |
49 |
| - char hexString[MAXCHAR]; |
| 43 | + int result; |
| 44 | + char s[MAXLEN]; |
50 | 45 |
|
51 | 46 | printf("Enter a hexadecimal string: ");
|
52 |
| - scanf("%s", hexString); |
| 47 | + scanf("%s", s); |
| 48 | + |
| 49 | + if ((result = htoi(s)) < 0) |
| 50 | + return -1; /* not a hexadecimal number */ |
53 | 51 |
|
54 |
| - value = htoi(hexString); |
55 |
| - printf("%i\n", value); |
| 52 | + printf("%i\n", result); |
56 | 53 |
|
57 | 54 | return 0;
|
58 | 55 | }
|
0 commit comments