-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathex0.c
92 lines (80 loc) · 1.97 KB
/
ex0.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 <assert.h>
#include <math.h>
int verify_base(char c, int base) {
if ((c - '0' > base) || (c - '0' < 0)) {
if (base > 10) {
if ((c - 'a' > base - 10) || (c - 'a' < 0)) {
printf("> Invalid number!");
return 0;
}
}
else {
printf("> Invalid number!");
return 0;
}
}
return 1;
}
unsigned int base_to_dec(char c) {
if (c - '0' <= 10) {
return (unsigned int)(c - '0');
} else {
return 10 + (unsigned int)(c - 'a');
}
}
char dec_to_base(unsigned int num, unsigned int base) {
int digit = num%base;
if (digit >= 10) {
return 'a' + (digit - 10);
}
return (char)digit;
}
void print_dec_in_base_rec(unsigned int num, unsigned int base) {
char c;
if (num == 0) {
return;
}
c = dec_to_base(num, base);
print_dec_in_base_rec(num / base, base);
printf("%u", c);
}
unsigned int get_dec_input(unsigned int base) {
unsigned int num = 0;
char c;
do {
c = getchar();
if ((c != '\n') && (c != EOF)) {
assert(verify_base(c, base) == 1);
num *= base;
num += base_to_dec(c);
}
} while ((c != '\n')&& (c != EOF));
return num;
}
int main() {
unsigned int a = 0, b = 0, num = 0;
printf("> Please enter the numbers base:\n");
scanf("%u", &a);
if (a > 16 || a < 2) {
printf("> Invalid input base");
assert((16 >= a) && (a >= 2));
}
printf("> Please enter the desired base:\n");
scanf("%u", &b);
if (b > 16 || b < 2) {
printf("> Invalid desired base");
assert((16 >= b) && (b >= 2));
}
printf("> Please enter a number in base %u:\n", a);
getchar();
num = get_dec_input(a);
printf("> The result is: ");
if (num == 0) {
printf("%u", num);
} else {
print_dec_in_base_rec(num, b);
}
printf("\n");
return 0;
}