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
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXLEN 100
/* converts n to string in base b representation */
void itob(int n, char s[], int b);
int main(int argc, char *argv[]) {
int n, b, c, i;
char s[MAXLEN];
printf("Number: ");
for (i = 0; i < MAXLEN - 1 && (c = getchar()) != '\n' && c != EOF; i++)
s[i] = c;
s[i] = 0;
n = atoi(s);
printf("Base: ");
for (i = 0; i < MAXLEN - 1 && (c = getchar()) != '\n' && c != EOF; i++)
s[i] = c;
s[i] = 0;
b = atoi(s);
itob(n, s, b);
printf("%d in base %d: %s\n", n, b, s);
return 0;
}
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;
}
}
void itob(int n, char s[], int b) {
int i, sign, mod;
i = 0;
sign = n < 0;
if (n >= 0) {
do {
mod = (n % b);
if (mod < 10)
s[i++] = mod + '0';
else
s[i++] = mod - 10 + 'A';
} while ((n /= b) > 0);
} else {
do {
mod = -(n % b);
if (mod < 10)
s[i++] = mod + '0';
else
s[i++] = mod - 10 + 'A';
} while ((n /= b) <= -1);
}
if (sign)
s[i++] = '-';
s[i] = 0;
reverse(s);
}
|