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