-
Notifications
You must be signed in to change notification settings - Fork 67
/
ex_3-5.c
81 lines (67 loc) · 1.51 KB
/
ex_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
70
71
72
73
74
75
76
77
78
79
80
81
#include <stdio.h>
#include <string.h>
int itob(int n, char s[], int b);
void reverse(char s[]);
void print_array(char s[])
{
int i;
for(i = 0; i < strlen(s); i++)
printf("%c", s[i]);
printf("\n");
}
//main displays same number from base of two to highest base
int main()
{
int base, number = 16384;
char ans[255] = { '\0' };
for(base = 2; base < 62; ++base)
{
if(itob(number, ans, base))
{
printf("Number: %d\tBase: %d Ans: ", number, base);
print_array(ans);
}
}
return 0;
}
int itob(int n, char s[], int b)
{
int sign, i = 0;
//create string of digits used to represent chars
char base_chars[] = { "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" };
//check that base is neither too high nor too small
if(b < 2)
{
printf("Base must be between 2 and %d.\n", (int)strlen(base_chars)-1);
return -1;
}
if(b > strlen(base_chars)-1)
{
printf("Base must be %d or less.\n", (int)strlen(base_chars)-1);
return -1;
}
// remove sign from number
if(n < 0) { n = -n; sign = 1; }
// increment s array and store in that location the modulus of the number -vs- the base
// while number divided by base is larger than 0
i = 0;
do {
s[i++] = base_chars[n % b];
} while ((n /= b) > 0);
// add sign from above
if(sign == '1') { s[++i] = '-'; }
s[i] = '\0';
reverse(s);
return 1;
}
// reverse string created (it was created in reverse order)
void reverse(char s[])
{
int temp, i, j;
for(i = 0, j = strlen(s)-1; j > i; i++, j--)
{
temp = s[i];
s[i] = s[j];
s[j] = temp;
}
}