1/* $NetBSD: bn_mp_toradix_n.c,v 1.1.1.1 2011/04/13 18:14:55 elric Exp $ */ 2 3#include <tommath.h> 4#ifdef BN_MP_TORADIX_N_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) 21 * 22 * Stores upto maxlen-1 chars and always a NULL byte 23 */ 24int mp_toradix_n(mp_int * a, char *str, int radix, int maxlen) 25{ 26 int res, digs; 27 mp_int t; 28 mp_digit d; 29 char *_s = str; 30 31 /* check range of the maxlen, radix */ 32 if (maxlen < 2 || radix < 2 || radix > 64) { 33 return MP_VAL; 34 } 35 36 /* quick out if its zero */ 37 if (mp_iszero(a) == MP_YES) { 38 *str++ = '0'; 39 *str = '\0'; 40 return MP_OKAY; 41 } 42 43 if ((res = mp_init_copy (&t, a)) != MP_OKAY) { 44 return res; 45 } 46 47 /* if it is negative output a - */ 48 if (t.sign == MP_NEG) { 49 /* we have to reverse our digits later... but not the - sign!! */ 50 ++_s; 51 52 /* store the flag and mark the number as positive */ 53 *str++ = '-'; 54 t.sign = MP_ZPOS; 55 56 /* subtract a char */ 57 --maxlen; 58 } 59 60 digs = 0; 61 while (mp_iszero (&t) == 0) { 62 if (--maxlen < 1) { 63 /* no more room */ 64 break; 65 } 66 if ((res = mp_div_d (&t, (mp_digit) radix, &t, &d)) != MP_OKAY) { 67 mp_clear (&t); 68 return res; 69 } 70 *str++ = mp_s_rmap[d]; 71 ++digs; 72 } 73 74 /* reverse the digits of the string. In this case _s points 75 * to the first digit [exluding the sign] of the number 76 */ 77 bn_reverse ((unsigned char *)_s, digs); 78 79 /* append a NULL so the string is properly terminated */ 80 *str = '\0'; 81 82 mp_clear (&t); 83 return MP_OKAY; 84} 85 86#endif 87 88/* Source: /cvs/libtom/libtommath/bn_mp_toradix_n.c,v */ 89/* Revision: 1.5 */ 90/* Date: 2006/12/28 01:25:13 */ 91