Skip to content

Commit 4ba8d82

Browse files
committed
improve answer
1 parent 2af0edc commit 4ba8d82

File tree

1 file changed

+24
-27
lines changed

1 file changed

+24
-27
lines changed

chapter02/2-3.c

Lines changed: 24 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -3,56 +3,53 @@
33
* hexadecimal digits (including an optional 0x or 0X) into its equivalent
44
* integer value. The allowable digits are 0 through 9, a through f, and A
55
* through F.
6+
*
67
* By Faisal Saadatmand
78
*/
89

910
#include <stdio.h>
11+
#include <ctype.h>
1012

11-
#define MAXCHAR 100
13+
#define MAXLEN 1000
1214

1315
/* functions */
1416
int htoi(char []);
1517

1618
int htoi(char s[])
1719
{
18-
int i, isValid, hexDigit, intValue;
20+
int i, hexDigit, intValue;
1921

22+
/* detect optional 0x or 0X prefix */
2023
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*/
2536
}
2637

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-
}
4338
return intValue;
4439
}
4540

4641
int main(void)
4742
{
48-
int value;
49-
char hexString[MAXCHAR];
43+
int result;
44+
char s[MAXLEN];
5045

5146
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 */
5351

54-
value = htoi(hexString);
55-
printf("%i\n", value);
52+
printf("%i\n", result);
5653

5754
return 0;
5855
}

0 commit comments

Comments
 (0)