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