Blob


1 /*
2 * Exercise 3-5. Write the function itob(n,s,b) that converts the integer n
3 * into a base b character representation in the string s. In particular,
4 * itob(n,s,16) formats n tas a hexadecimal integer in s.
5 */
7 #include <stdio.h>
8 #include <stdlib.h>
9 #include <limits.h>
10 #include <string.h>
12 int pow(int x, int n) {
13 int val;
14 for (val = 1; n > 0; n--) {
15 val *= x;
16 }
17 return val;
18 }
19 int itob(int n, char *s, int b) {
20 char *tr = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
21 int digits;
22 for (digits = 0; pow(b,digits) <= n; digits++)
23 ;
24 for (int i = digits-1; i >= 0; i--) {
25 int times = (n/pow(b,i));
26 *s++ = *(tr + times);
27 n -= times * pow(b,i);
28 }
29 *s = '\0';
30 return 0;
31 }
32 int assert(char *expect, char *actual) {
33 printf("Expect: %s\n", expect);
34 printf("Actual: %s\n", actual);
35 return strcmp(expect, actual);
36 }
37 int main() {
38 char s[100];
39 char *t;
40 sprintf(t, "%d", pow(9,9));
41 assert("387420489", t);
42 itob(1208, s, 26);
43 assert("1KC", s);
44 itob(5763, s, 16);
45 assert("1683", s);
46 itob(194200, s, 8);
47 assert("573230", s);
48 itob(2, s, 8);
49 assert("2", s);
50 itob(8, s, 2);
51 assert("1000", s);
52 itob(93, s, 2);
53 assert("1011101", s);
54 /*
55 * overflow issues
56 sprintf(t, "%x", INT_MAX);
57 itob(INT_MAX, s, 16);
58 assert(t, s);
59 */
60 }
62 /*
63 * thought process:
64 * 1208/26
65 * 46.46153846153846153846
66 * too big, repeat division
67 * 1208/26/26
68 * 1.78698224852071005917
69 * base 26: 0100
70 * 1 + modulo
71 * 26*26 = 676
72 * 1208 - 676 = 532
73 * 532 / 26 = 20
74 * lookup 20 (char 9abcdefghijk)
75 * base 26: 01k0 + modulo
76 * 532 - 20*26 = 12
77 * lookup 20 (char c)
78 * base 26: 01kc
79 * 5763/16 = 360.18
80 * too big, repeat division
81 * 5763/16/16 = 22.511
82 * too big, repeat division
83 * 5763/16/16/16 = 1.406
84 * base 16: 1 + modulo
85 * 5763-1*16*16*16 = 1667
86 * 1667/16/16 = 6.5117
87 * 1667-6*16*16 = 131
88 * base 16: 16 + modulo
89 * 131/16 = 8.1875
90 * 131-8*16 = 3
91 * base 16: 163
92 * 194200/8/8/8/8/8 = 5.926
93 * 194200 - 5*8^5 = 30360
94 * 30360/8/8/8/8 = 7.41
95 * 30360 - 7*8^4 = 1688
96 * 1688/8/8/8 = 3.2968
97 * 1688 - 3*8^3 = 152
98 * 152/8/8 = 2.375
99 * 152 - 2*8^2 = 24
100 * 24/8 = 3
101 * base 8: 573230
102 */
104 /*
105 itob(INT_MIN, s, 2);
106 printf("Expect: %s\n", "");
107 printf("Actual: %s\n", s);
108 itob(-5, s, 8);
109 printf("Expect: %s\n", "");
110 printf("Actual: %s\n", s);
111 */