Mercurial > dropbear
annotate bn_mp_read_radix.c @ 190:d8254fc979e9 libtommath-orig LTM_0.35
Initial import of libtommath 0.35
author | Matt Johnston <matt@ucc.asn.au> |
---|---|
date | Fri, 06 May 2005 08:59:30 +0000 |
parents | d29b64170cf0 |
children |
rev | line source |
---|---|
142 | 1 #include <tommath.h> |
2 #ifdef BN_MP_READ_RADIX_C | |
2 | 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, [email protected], http://math.libtomcrypt.org | |
16 */ | |
17 | |
18 /* read a string [ASCII] in a given radix */ | |
190
d8254fc979e9
Initial import of libtommath 0.35
Matt Johnston <matt@ucc.asn.au>
parents:
142
diff
changeset
|
19 int mp_read_radix (mp_int * a, const char *str, int radix) |
2 | 20 { |
21 int y, res, neg; | |
22 char ch; | |
23 | |
24 /* make sure the radix is ok */ | |
25 if (radix < 2 || radix > 64) { | |
26 return MP_VAL; | |
27 } | |
28 | |
29 /* if the leading digit is a | |
30 * minus set the sign to negative. | |
31 */ | |
32 if (*str == '-') { | |
33 ++str; | |
34 neg = MP_NEG; | |
35 } else { | |
36 neg = MP_ZPOS; | |
37 } | |
38 | |
39 /* set the integer to the default of zero */ | |
40 mp_zero (a); | |
41 | |
42 /* process each digit of the string */ | |
43 while (*str) { | |
44 /* if the radix < 36 the conversion is case insensitive | |
45 * this allows numbers like 1AB and 1ab to represent the same value | |
46 * [e.g. in hex] | |
47 */ | |
48 ch = (char) ((radix < 36) ? toupper (*str) : *str); | |
49 for (y = 0; y < 64; y++) { | |
50 if (ch == mp_s_rmap[y]) { | |
51 break; | |
52 } | |
53 } | |
54 | |
55 /* if the char was found in the map | |
56 * and is less than the given radix add it | |
57 * to the number, otherwise exit the loop. | |
58 */ | |
59 if (y < radix) { | |
60 if ((res = mp_mul_d (a, (mp_digit) radix, a)) != MP_OKAY) { | |
61 return res; | |
62 } | |
63 if ((res = mp_add_d (a, (mp_digit) y, a)) != MP_OKAY) { | |
64 return res; | |
65 } | |
66 } else { | |
67 break; | |
68 } | |
69 ++str; | |
70 } | |
71 | |
72 /* set the sign only if a != 0 */ | |
73 if (mp_iszero(a) != 1) { | |
74 a->sign = neg; | |
75 } | |
76 return MP_OKAY; | |
77 } | |
142 | 78 #endif |