forked from jhpy1024/CProgrammingLanguageExercises
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexercise_3-5.c
69 lines (56 loc) · 983 Bytes
/
exercise_3-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
#include <stdio.h>
#include <string.h>
enum
{
HEXADECIMAL = 16,
BINARY = 2
};
void reverse(char str[])
{
char tmp = '\0';
for (int i = 0, j = strlen(str) - 1; i < j; ++i, --j)
{
tmp = str[i];
str[i] = str[j];
str[j] = tmp;
}
}
void itob(int num, int base, char str[])
{
int index = 0;
int sign = num;
if (sign < 0)
{
num = -num;
}
do
{
int digit = num % base;
if (digit >= 10)
{
str[index++] = (digit - 10) + 'A';
}
else
{
str[index++] = digit + '0';
}
}
while ((num /= base) > 0);
if (sign < 0)
{
str[index++] = '-';
}
str[index] = '\0';
reverse(str);
}
int main()
{
int num = 42;
char str[100] = { 0 };
for (int base = 2; base <= 16; ++base)
{
itob(num, base, str);
printf("%d to base %d = %s\n", num, base, str);
}
return 0;
}