bn_mp_toradix_n.c

Go to the documentation of this file.
00001 #include <tommath.h>
00002 #ifdef BN_MP_TORADIX_N_C
00003 /* LibTomMath, multiple-precision integer library -- Tom St Denis
00004  *
00005  * LibTomMath is a library that provides multiple-precision
00006  * integer arithmetic as well as number theoretic functionality.
00007  *
00008  * The library was designed directly after the MPI library by
00009  * Michael Fromberger but has been written from scratch with
00010  * additional optimizations in place.
00011  *
00012  * The library is free for all purposes without any express
00013  * guarantee it works.
00014  *
00015  * Tom St Denis, tomstdenis@gmail.com, http://math.libtomcrypt.com
00016  */
00017 
00018 /* stores a bignum as a ASCII string in a given radix (2..64) 
00019  *
00020  * Stores upto maxlen-1 chars and always a NULL byte 
00021  */
00022 int mp_toradix_n(mp_int * a, char *str, int radix, int maxlen)
00023 {
00024   int     res, digs;
00025   mp_int  t;
00026   mp_digit d;
00027   char   *_s = str;
00028 
00029   /* check range of the maxlen, radix */
00030   if (maxlen < 2 || radix < 2 || radix > 64) {
00031     return MP_VAL;
00032   }
00033 
00034   /* quick out if its zero */
00035   if (mp_iszero(a) == MP_YES) {
00036      *str++ = '0';
00037      *str = '\0';
00038      return MP_OKAY;
00039   }
00040 
00041   if ((res = mp_init_copy (&t, a)) != MP_OKAY) {
00042     return res;
00043   }
00044 
00045   /* if it is negative output a - */
00046   if (t.sign == MP_NEG) {
00047     /* we have to reverse our digits later... but not the - sign!! */
00048     ++_s;
00049 
00050     /* store the flag and mark the number as positive */
00051     *str++ = '-';
00052     t.sign = MP_ZPOS;
00053  
00054     /* subtract a char */
00055     --maxlen;
00056   }
00057 
00058   digs = 0;
00059   while (mp_iszero (&t) == 0) {
00060     if (--maxlen < 1) {
00061        /* no more room */
00062        break;
00063     }
00064     if ((res = mp_div_d (&t, (mp_digit) radix, &t, &d)) != MP_OKAY) {
00065       mp_clear (&t);
00066       return res;
00067     }
00068     *str++ = mp_s_rmap[d];
00069     ++digs;
00070   }
00071 
00072   /* reverse the digits of the string.  In this case _s points
00073    * to the first digit [exluding the sign] of the number
00074    */
00075   bn_reverse ((unsigned char *)_s, digs);
00076 
00077   /* append a NULL so the string is properly terminated */
00078   *str = '\0';
00079 
00080   mp_clear (&t);
00081   return MP_OKAY;
00082 }
00083 
00084 #endif
00085 
00086 /* $Source: /cvsroot/tcl/libtommath/bn_mp_toradix_n.c,v $ */
00087 /* $Revision: 1.1.1.4 $ */
00088 /* $Date: 2006/12/01 00:08:11 $ */



Generated on Wed Mar 12 12:18:25 2008 by  doxygen 1.5.1