1 /* $NetBSD: bn_mp_toradix.c,v 1.2 2017/01/28 21:31:47 christos Exp $ */
2
3 #include <tommath.h>
4 #ifdef BN_MP_TORADIX_C
5 /* LibTomMath, multiple-precision integer library -- Tom St Denis
6 *
7 * LibTomMath is a library that provides multiple-precision
8 * integer arithmetic as well as number theoretic functionality.
9 *
10 * The library was designed directly after the MPI library by
11 * Michael Fromberger but has been written from scratch with
12 * additional optimizations in place.
13 *
14 * The library is free for all purposes without any express
15 * guarantee it works.
16 *
17 * Tom St Denis, tomstdenis@gmail.com, http://libtom.org
18 */
19
20 /* stores a bignum as a ASCII string in a given radix (2..64) */
mp_toradix(mp_int * a,char * str,int radix)21 int mp_toradix (mp_int * a, char *str, int radix)
22 {
23 int res, digs;
24 mp_int t;
25 mp_digit d;
26 char *_s = str;
27
28 /* check range of the radix */
29 if (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 ++_s;
47 *str++ = '-';
48 t.sign = MP_ZPOS;
49 }
50
51 digs = 0;
52 while (mp_iszero (&t) == 0) {
53 if ((res = mp_div_d (&t, (mp_digit) radix, &t, &d)) != MP_OKAY) {
54 mp_clear (&t);
55 return res;
56 }
57 *str++ = mp_s_rmap[d];
58 ++digs;
59 }
60
61 /* reverse the digits of the string. In this case _s points
62 * to the first digit [exluding the sign] of the number]
63 */
64 bn_reverse ((unsigned char *)_s, digs);
65
66 /* append a NULL so the string is properly terminated */
67 *str = '\0';
68
69 mp_clear (&t);
70 return MP_OKAY;
71 }
72
73 #endif
74
75 /* Source: /cvs/libtom/libtommath/bn_mp_toradix.c,v */
76 /* Revision: 1.4 */
77 /* Date: 2006/12/28 01:25:13 */
78