-
Notifications
You must be signed in to change notification settings - Fork 0
/
ex3-5.c
92 lines (82 loc) · 1.69 KB
/
ex3-5.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
#include <stdio.h>
#include <limits.h>
#include <string.h>
/* reverse: reverse string s in place */
void reverse(char s[]) {
int c, i, j;
for (i = 0, j = strlen(s)-1; i < j; i++, j--) {
c = s[i];
s[i] = s[j];
s[j] = c;
}
}
/* convert the integer n into a base b character representation in the string s, handles INT_MIN correctly. 2 <= b <= 10*/
void itob(int n, char s[], int b) {
int i = 0, sign = n;
unsigned value;
if (n == INT_MIN) {
value = (unsigned) INT_MAX + 1;
}
else if (n < 0) {
value = -n;
}
else {
value = n;
}
do {
s[i++] = value % b + '0';
} while ((value /= b) > 0);
if (sign < 0)
s[i++] = '-';
s[i] = '\0';
reverse(s);
}
/* convert the integer n into a hexadecimal integer */
void itoh(int n, char s[], int b) {
int i = 0, sign = n;
unsigned value;
int modulo;
if (n == INT_MIN) {
value = (unsigned) INT_MAX + 1;
}
else if (n < 0) {
value = -n;
}
else {
value = n;
}
do {
modulo = value % 16;
if (modulo < 10) {
s[i++] = modulo + '0';
}
else if (modulo == 10) {
s[i++] = 'A';
}
else if (modulo == 11) {
s[i++] = 'B';
}
else if (modulo == 12) {
s[i++] = 'C';
}
else if (modulo == 13) {
s[i++] = 'D';
}
else if (modulo == 14) {
s[i++] = 'E';
}
else if (modulo == 15) {
s[i++] = 'F';
}
} while ((value /= 16) > 0);
if (sign < 0)
s[i++] = '-';
s[i] = '\0';
reverse(s);
}
int main() {
int n = INT_MIN;
char s[40];
itoh(n, s, 16);
printf("%s\n", s);
}