comparison bn_mp_toradix.c @ 1:22d5cf7d4b1a libtommath

Renaming branch
author Matt Johnston <matt@ucc.asn.au>
date Mon, 31 May 2004 18:23:46 +0000
parents
children d29b64170cf0
comparison
equal deleted inserted replaced
-1:000000000000 1:22d5cf7d4b1a
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 int mp_toradix (mp_int * a, char *str, int radix)
19 {
20 int res, digs;
21 mp_int t;
22 mp_digit d;
23 char *_s = str;
24
25 /* check range of the radix */
26 if (radix < 2 || radix > 64) {
27 return MP_VAL;
28 }
29
30 /* quick out if its zero */
31 if (mp_iszero(a) == 1) {
32 *str++ = '0';
33 *str = '\0';
34 return MP_OKAY;
35 }
36
37 if ((res = mp_init_copy (&t, a)) != MP_OKAY) {
38 return res;
39 }
40
41 /* if it is negative output a - */
42 if (t.sign == MP_NEG) {
43 ++_s;
44 *str++ = '-';
45 t.sign = MP_ZPOS;
46 }
47
48 digs = 0;
49 while (mp_iszero (&t) == 0) {
50 if ((res = mp_div_d (&t, (mp_digit) radix, &t, &d)) != MP_OKAY) {
51 mp_clear (&t);
52 return res;
53 }
54 *str++ = mp_s_rmap[d];
55 ++digs;
56 }
57
58 /* reverse the digits of the string. In this case _s points
59 * to the first digit [exluding the sign] of the number]
60 */
61 bn_reverse ((unsigned char *)_s, digs);
62
63 /* append a NULL so the string is properly terminated */
64 *str = '\0';
65
66 mp_clear (&t);
67 return MP_OKAY;
68 }
69