1
|
1 /* LibTomMath, multiple-precision integer library -- Tom St Denis |
|
2 * |
|
3 * LibTomMath is a library that provides multiple-precision |
|
4 * integer arithmetic as well as number theoretic functionality. |
|
5 * |
|
6 * The library was designed directly after the MPI library by |
|
7 * Michael Fromberger but has been written from scratch with |
|
8 * additional optimizations in place. |
|
9 * |
|
10 * The library is free for all purposes without any express |
|
11 * guarantee it works. |
|
12 * |
|
13 * Tom St Denis, [email protected], http://math.libtomcrypt.org |
|
14 */ |
|
15 #include <tommath.h> |
|
16 |
|
17 /* stores a bignum as a ASCII string in a given radix (2..64) |
|
18 * |
|
19 * Stores upto maxlen-1 chars and always a NULL byte |
|
20 */ |
|
21 int mp_toradix_n(mp_int * a, char *str, int radix, int maxlen) |
|
22 { |
|
23 int res, digs; |
|
24 mp_int t; |
|
25 mp_digit d; |
|
26 char *_s = str; |
|
27 |
|
28 /* check range of the maxlen, radix */ |
|
29 if (maxlen < 3 || radix < 2 || radix > 64) { |
|
30 return MP_VAL; |
|
31 } |
|
32 |
|
33 /* quick out if its zero */ |
|
34 if (mp_iszero(a) == 1) { |
|
35 *str++ = '0'; |
|
36 *str = '\0'; |
|
37 return MP_OKAY; |
|
38 } |
|
39 |
|
40 if ((res = mp_init_copy (&t, a)) != MP_OKAY) { |
|
41 return res; |
|
42 } |
|
43 |
|
44 /* if it is negative output a - */ |
|
45 if (t.sign == MP_NEG) { |
|
46 /* we have to reverse our digits later... but not the - sign!! */ |
|
47 ++_s; |
|
48 |
|
49 /* store the flag and mark the number as positive */ |
|
50 *str++ = '-'; |
|
51 t.sign = MP_ZPOS; |
|
52 |
|
53 /* subtract a char */ |
|
54 --maxlen; |
|
55 } |
|
56 |
|
57 digs = 0; |
|
58 while (mp_iszero (&t) == 0) { |
|
59 if ((res = mp_div_d (&t, (mp_digit) radix, &t, &d)) != MP_OKAY) { |
|
60 mp_clear (&t); |
|
61 return res; |
|
62 } |
|
63 *str++ = mp_s_rmap[d]; |
|
64 ++digs; |
|
65 |
|
66 if (--maxlen == 1) { |
|
67 /* no more room */ |
|
68 break; |
|
69 } |
|
70 } |
|
71 |
|
72 /* reverse the digits of the string. In this case _s points |
|
73 * to the first digit [exluding the sign] of the number] |
|
74 */ |
|
75 bn_reverse ((unsigned char *)_s, digs); |
|
76 |
|
77 /* append a NULL so the string is properly terminated */ |
|
78 *str = '\0'; |
|
79 |
|
80 mp_clear (&t); |
|
81 return MP_OKAY; |
|
82 } |
|
83 |