1 /*	$NetBSD: bn_mp_read_radix.c,v 1.1.1.1 2011/04/13 18:14:54 elric Exp $	*/
2 
3 #include <tommath.h>
4 #ifdef BN_MP_READ_RADIX_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 /* read a string [ASCII] in a given radix */
21 int mp_read_radix (mp_int * a, const char *str, int radix)
22 {
23   int     y, res, neg;
24   char    ch;
25 
26   /* zero the digit bignum */
27   mp_zero(a);
28 
29   /* make sure the radix is ok */
30   if (radix < 2 || radix > 64) {
31     return MP_VAL;
32   }
33 
34   /* if the leading digit is a
35    * minus set the sign to negative.
36    */
37   if (*str == '-') {
38     ++str;
39     neg = MP_NEG;
40   } else {
41     neg = MP_ZPOS;
42   }
43 
44   /* set the integer to the default of zero */
45   mp_zero (a);
46 
47   /* process each digit of the string */
48   while (*str) {
49     /* if the radix < 36 the conversion is case insensitive
50      * this allows numbers like 1AB and 1ab to represent the same  value
51      * [e.g. in hex]
52      */
53     ch = (char) ((radix < 36) ? toupper (*str) : *str);
54     for (y = 0; y < 64; y++) {
55       if (ch == mp_s_rmap[y]) {
56          break;
57       }
58     }
59 
60     /* if the char was found in the map
61      * and is less than the given radix add it
62      * to the number, otherwise exit the loop.
63      */
64     if (y < radix) {
65       if ((res = mp_mul_d (a, (mp_digit) radix, a)) != MP_OKAY) {
66          return res;
67       }
68       if ((res = mp_add_d (a, (mp_digit) y, a)) != MP_OKAY) {
69          return res;
70       }
71     } else {
72       break;
73     }
74     ++str;
75   }
76 
77   /* set the sign only if a != 0 */
78   if (mp_iszero(a) != 1) {
79      a->sign = neg;
80   }
81   return MP_OKAY;
82 }
83 #endif
84 
85 /* Source: /cvs/libtom/libtommath/bn_mp_read_radix.c,v */
86 /* Revision: 1.5 */
87 /* Date: 2006/12/28 01:25:13 */
88