1 /* $NetBSD: bn_mp_radix_size.c,v 1.1.1.1 2011/04/13 18:14:54 elric Exp $ */ 2 3 #include <tommath.h> 4 #ifdef BN_MP_RADIX_SIZE_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 /* returns size of ASCII reprensentation */ 21 int mp_radix_size (mp_int * a, int radix, int *size) 22 { 23 int res, digs; 24 mp_int t; 25 mp_digit d; 26 27 *size = 0; 28 29 /* special case for binary */ 30 if (radix == 2) { 31 *size = mp_count_bits (a) + (a->sign == MP_NEG ? 1 : 0) + 1; 32 return MP_OKAY; 33 } 34 35 /* make sure the radix is in range */ 36 if (radix < 2 || radix > 64) { 37 return MP_VAL; 38 } 39 40 if (mp_iszero(a) == MP_YES) { 41 *size = 2; 42 return MP_OKAY; 43 } 44 45 /* digs is the digit count */ 46 digs = 0; 47 48 /* if it's negative add one for the sign */ 49 if (a->sign == MP_NEG) { 50 ++digs; 51 } 52 53 /* init a copy of the input */ 54 if ((res = mp_init_copy (&t, a)) != MP_OKAY) { 55 return res; 56 } 57 58 /* force temp to positive */ 59 t.sign = MP_ZPOS; 60 61 /* fetch out all of the digits */ 62 while (mp_iszero (&t) == MP_NO) { 63 if ((res = mp_div_d (&t, (mp_digit) radix, &t, &d)) != MP_OKAY) { 64 mp_clear (&t); 65 return res; 66 } 67 ++digs; 68 } 69 mp_clear (&t); 70 71 /* return digs + 1, the 1 is for the NULL byte that would be required. */ 72 *size = digs + 1; 73 return MP_OKAY; 74 } 75 76 #endif 77 78 /* Source: /cvs/libtom/libtommath/bn_mp_radix_size.c,v */ 79 /* Revision: 1.5 */ 80 /* Date: 2006/12/28 01:25:13 */ 81