Home | History | Annotate | Download | only in libtommath
      1 #include <tommath.h>
      2 #ifdef BN_MP_READ_RADIX_C
      3 /* LibTomMath, multiple-precision integer library -- Tom St Denis
      4  *
      5  * LibTomMath is a library that provides multiple-precision
      6  * integer arithmetic as well as number theoretic functionality.
      7  *
      8  * The library was designed directly after the MPI library by
      9  * Michael Fromberger but has been written from scratch with
     10  * additional optimizations in place.
     11  *
     12  * The library is free for all purposes without any express
     13  * guarantee it works.
     14  *
     15  * Tom St Denis, tomstdenis (at) gmail.com, http://math.libtomcrypt.com
     16  */
     17 
     18 /* read a string [ASCII] in a given radix */
     19 int mp_read_radix (mp_int * a, const char *str, int radix)
     20 {
     21   int     y, res, neg;
     22   char    ch;
     23 
     24   /* zero the digit bignum */
     25   mp_zero(a);
     26 
     27   /* make sure the radix is ok */
     28   if (radix < 2 || radix > 64) {
     29     return MP_VAL;
     30   }
     31 
     32   /* if the leading digit is a
     33    * minus set the sign to negative.
     34    */
     35   if (*str == '-') {
     36     ++str;
     37     neg = MP_NEG;
     38   } else {
     39     neg = MP_ZPOS;
     40   }
     41 
     42   /* set the integer to the default of zero */
     43   mp_zero (a);
     44 
     45   /* process each digit of the string */
     46   while (*str) {
     47     /* if the radix < 36 the conversion is case insensitive
     48      * this allows numbers like 1AB and 1ab to represent the same  value
     49      * [e.g. in hex]
     50      */
     51     ch = (char) ((radix < 36) ? toupper (*str) : *str);
     52     for (y = 0; y < 64; y++) {
     53       if (ch == mp_s_rmap[y]) {
     54          break;
     55       }
     56     }
     57 
     58     /* if the char was found in the map
     59      * and is less than the given radix add it
     60      * to the number, otherwise exit the loop.
     61      */
     62     if (y < radix) {
     63       if ((res = mp_mul_d (a, (mp_digit) radix, a)) != MP_OKAY) {
     64          return res;
     65       }
     66       if ((res = mp_add_d (a, (mp_digit) y, a)) != MP_OKAY) {
     67          return res;
     68       }
     69     } else {
     70       break;
     71     }
     72     ++str;
     73   }
     74 
     75   /* set the sign only if a != 0 */
     76   if (mp_iszero(a) != 1) {
     77      a->sign = neg;
     78   }
     79   return MP_OKAY;
     80 }
     81 #endif
     82 
     83 /* $Source: /cvs/libtom/libtommath/bn_mp_read_radix.c,v $ */
     84 /* $Revision: 1.4 $ */
     85 /* $Date: 2006/03/31 14:18:44 $ */
     86