|
7 | 7 | */
|
8 | 8 |
|
9 | 9 | #include <stdio.h>
|
10 |
| -#include <ctype.h> /* for htoi() */ |
11 |
| -#include <math.h> /* for pow() */ |
12 |
| -#include <string.h> |
13 | 10 |
|
14 |
| -#define MAXLINE 1000 |
| 11 | +#define MAXCHAR 100 |
15 | 12 |
|
16 | 13 | /* functions */
|
17 |
| -long unsigned htoi(char []); |
| 14 | +int htoi(char []); |
18 | 15 |
|
19 |
| -long unsigned htoi(char s[]) |
| 16 | +int htoi(char s[]) |
20 | 17 | {
|
21 |
| - int i, len; |
22 |
| - long unsigned intValue = 0; |
23 |
| - int base10; |
24 |
| - |
25 |
| - len = strlen(s); |
| 18 | + int i, isValid, hexDigit, intValue; |
26 | 19 |
|
27 | 20 | i = 0;
|
28 |
| - if (s[i] == '0' && (s[i + 1] == 'x' || s[i + 1] == 'X')) { |
29 |
| - i += 2; |
30 |
| - len -= 2; |
| 21 | + if (s[i] == '0') { |
| 22 | + ++i; |
| 23 | + if (s[i] == 'x' || s[i] == 'X') |
| 24 | + ++i; |
31 | 25 | }
|
32 | 26 |
|
33 |
| - for ( ; s[i] != '\0'; i++, len--) { |
34 |
| - |
35 |
| - if (!isxdigit(s[i])) |
36 |
| - return -1; |
37 |
| - |
38 |
| - if (isdigit(s[i])) |
39 |
| - base10 = s[i] - '0'; |
40 |
| - else if (s[i] == 'a') |
41 |
| - base10 = 10; |
42 |
| - else if (s[i] == 'b') |
43 |
| - base10 = 11; |
44 |
| - else if (s[i] == 'c') |
45 |
| - base10 = 12; |
46 |
| - else if (s[i] == 'd') |
47 |
| - base10 = 13; |
48 |
| - else if (s[i] == 'e') |
49 |
| - base10 = 14; |
50 |
| - else if (s[i] == 'f') |
51 |
| - base10 = 15; |
52 |
| - else if (s[i] == 'A') |
53 |
| - base10 = 10; |
54 |
| - else if (s[i] == 'B') |
55 |
| - base10 = 11; |
56 |
| - else if (s[i] == 'C') |
57 |
| - base10 = 12; |
58 |
| - else if (s[i] == 'D') |
59 |
| - base10 = 13; |
60 |
| - else if (s[i] == 'E') |
61 |
| - base10 = 14; |
62 |
| - else if (s[i] == 'F') |
63 |
| - base10 = 15; |
64 |
| - |
65 |
| - intValue += pow(16, len - 1) * base10; |
| 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; |
66 | 42 | }
|
67 | 43 | return intValue;
|
68 | 44 | }
|
69 | 45 |
|
70 | 46 | int main(void)
|
71 | 47 | {
|
72 |
| - unsigned long intValue; |
73 |
| - char xString[MAXLINE]; |
| 48 | + int value; |
| 49 | + char hexString[MAXCHAR]; |
74 | 50 |
|
75 | 51 | printf("Enter a hexadecimal string: ");
|
76 |
| - scanf("%s", xString); |
| 52 | + scanf("%s", hexString); |
| 53 | + |
| 54 | + value = htoi(hexString); |
| 55 | + printf("%i\n", value); |
77 | 56 |
|
78 |
| - if ((intValue = htoi(xString)) < 0) |
79 |
| - printf("Invalid hexadecimal number\n"); |
80 |
| - else |
81 |
| - printf("%lu\n", intValue); |
82 | 57 | return 0;
|
83 | 58 | }
|
0 commit comments