-
Notifications
You must be signed in to change notification settings - Fork 0
/
exercise_2-3.c
113 lines (59 loc) · 1.74 KB
/
exercise_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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#include <stdio.h>
#include <math.h>
#include <string.h>
/*
Usage:
For char hex[],
input a hexadecimal
string. It may begin
with "0x" or "0X"
and immediately
followed by hexadecimal
digits, including from
'A' to 'F'. The
letters can be uppercase or
lowercase.
How it Works:
Does the following equation from
RIGHT TO LEFT:
16^n*b_n + 16^(n-1)*b_(n-1) + 16^(n-2)*b_(n-2) + .. 16^0*b_0
<--- <--- <--- <--- <--- <--- <--- <--- <----
Understand the following
char c = 'A';
(c - 'A') == ((int)0) NOT '0'
C compiler will automatically convert char
to an int when you apply an arithmetic
operator to it and another char.
*/
int htoi(char *s) {
char *zero_value = s;
int base;
int exp = 0;
int decimal = 0;
char *right = (s + (strlen(s)-1) );
while ( right >= zero_value) {
if (*right == 'X' || *right == 'x') {
break;
}
else if (*right>= 'A' && *right <= 'F') {
base = ((*right -'A')+10);
decimal = ((int)pow(16,exp++))*base + decimal;
}
else if (*right>= 'a' && *right <= 'f') {
base = ((*right -'a')+10);
decimal = ((int)pow(16,exp++))*base + decimal;
}
else {
// regular digit from '0' to '9'
base = ((*right - '0'));
decimal = ((int)pow(16,exp++))*base + decimal;
}
right--;
}
return decimal;
}
int main() {
char hex[] = "0XaBc";
int ans = htoi(hex);
printf("%d\n", ans);
}