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.
12 int pow(int x, int n) {
14 for (val = 1; n > 0; n--) {
19 int itob(int n, char *s, int b) {
20 char *tr = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
22 for (digits = 0; pow(b,digits) <= n; digits++)
24 for (int i = digits-1; i >= 0; i--) {
25 int times = (n/pow(b,i));
27 n -= times * pow(b,i);
32 int assert(char *expect, char *actual) {
33 printf("Expect: %s\n", expect);
34 printf("Actual: %s\n", actual);
35 return strcmp(expect, actual);
40 sprintf(t, "%d", pow(9,9));
41 assert("387420489", t);
56 sprintf(t, "%x", INT_MAX);
65 * 46.46153846153846153846
66 * too big, repeat division
68 * 1.78698224852071005917
74 * lookup 20 (char 9abcdefghijk)
75 * base 26: 01k0 + modulo
80 * too big, repeat division
82 * too big, repeat division
83 * 5763/16/16/16 = 1.406
85 * 5763-1*16*16*16 = 1667
88 * base 16: 16 + modulo
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
106 printf("Expect: %s\n", "");
107 printf("Actual: %s\n", s);
109 printf("Expect: %s\n", "");
110 printf("Actual: %s\n", s);