|
|
1.1 root 1: #include "mprec.h"
2: #include <assert.h>
3:
4:
5: /*
6: * Sizfac is an array whoose obase - 2 component contains the
7: * maximum number of characters needed per byte of mint when
8: * converted to a string in base obase. This simply means that
9: * sizfac[obase - 2] contains the log (base obase) of BASE, rounded
10: * up.
11: */
12:
13: static int sizfac[] = {
14: 7, /* 2^7 = 128 */
15: 5, /* 3^5 = 243 */
16: 4, /* 4^4 = 256 */
17: 3, /* 5^3 = 125 */
18: 3, /* 6^3 = 216 */
19: 3, /* 7^3 = 343 */
20: 3, /* 8^3 = 512 */
21: 3, /* 9^3 = 729 */
22: 3, /* 10^3 = 1000 */
23: 3, /* 11^3 = 1331 */
24: 2, /* 12^2 = 144 */
25: 2, /* 13^2 = 169 */
26: 2, /* 14^2 = 196 */
27: 2, /* 15^2 = 225 */
28: 2 /* 16^2 = 256 */
29: };
30:
31:
32: /*
33: * Dtc is an array of characters indexed by the allowable
34: * digist (0 to 15). Dtc[i] is the character to represent
35: * the digit i.
36: */
37:
38: static char dtc[] = {
39: '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
40: 'A', 'B', 'C', 'D', 'E', 'F'
41: };
42:
43:
44: /*
45: * Obase is a int which is the output base used by mtos. The value
46: * of obase shoud be between 2 and 16. For bases greater than 10
47: * the characters A to F are used as digits.
48: */
49:
50: int obase = 10;
51:
52:
53: /*
54: * Mtos converts the mint pointed to by "a" into a string of characters
55: * in base obase. It returns a pointer to that string. Note that
56: * obase is assumed to satisfy 2 <= obase <= 16.
57: * Also note that space for the string is allocated useing mpalc so
58: * that to release the space, the caller should use mpfree.
59: */
60:
61: char *
62: mtos(a)
63: mint *a;
64: {
65: register char *rp, *to;
66: mint ac;
67: int mifl;
68: int dig;
69: unsigned size;
70: char *res;
71:
72: assert(2 <= obase <= 16);
73:
74: /* set ac = abs(a), copying if necessary */
75: minit(&ac);
76: if (mifl = ispos(a))
77: mcopy(a, &ac);
78: else
79: mneg(a, &ac);
80:
81: /* calculate maximum size of result and allocate space */
82: size = 1 + ac.len * sizfac[obase - 2];
83: if (!mifl)
84: ++size;
85: res = (char *)mpalc(size);
86: if (res == NULL)
87: mperr("No space for string.");
88:
89: /* create string - from back to front */
90: rp = res + size;
91: *--rp = '\0';
92: do {
93: sdiv(&ac, obase, &ac, &dig);
94: *--rp = dtc[dig];
95: } while (!zerop(&ac));
96: mpfree(ac.val);
97: if (!mifl)
98: *--rp = '-';
99: assert(rp >= res);
100:
101: /* left justify string if necessary */
102: if (rp != res) {
103: to = res;
104: while ((*to++ = *rp++) != '\0')
105: ;
106: }
107:
108: return(res);
109: }
This archive runs on limited infrastructure. Preserving old code on modern bandwidth. Automated agents are requested to crawl responsibly.