Skip to content

Commit 5963868

Browse files
committed
Improve solution
1 parent c7b0d71 commit 5963868

File tree

1 file changed

+29
-54
lines changed

1 file changed

+29
-54
lines changed

chapter02/2-3.c

Lines changed: 29 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -7,77 +7,52 @@
77
*/
88

99
#include <stdio.h>
10-
#include <ctype.h> /* for htoi() */
11-
#include <math.h> /* for pow() */
12-
#include <string.h>
1310

14-
#define MAXLINE 1000
11+
#define MAXCHAR 100
1512

1613
/* functions */
17-
long unsigned htoi(char []);
14+
int htoi(char []);
1815

19-
long unsigned htoi(char s[])
16+
int htoi(char s[])
2017
{
21-
int i, len;
22-
long unsigned intValue = 0;
23-
int base10;
24-
25-
len = strlen(s);
18+
int i, isValid, hexDigit, intValue;
2619

2720
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;
3125
}
3226

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;
6642
}
6743
return intValue;
6844
}
6945

7046
int main(void)
7147
{
72-
unsigned long intValue;
73-
char xString[MAXLINE];
48+
int value;
49+
char hexString[MAXCHAR];
7450

7551
printf("Enter a hexadecimal string: ");
76-
scanf("%s", xString);
52+
scanf("%s", hexString);
53+
54+
value = htoi(hexString);
55+
printf("%i\n", value);
7756

78-
if ((intValue = htoi(xString)) < 0)
79-
printf("Invalid hexadecimal number\n");
80-
else
81-
printf("%lu\n", intValue);
8257
return 0;
8358
}

0 commit comments

Comments
 (0)