comparison libtommath/bn_mp_read_radix.c @ 330:5488db2e9e4e

merge of 332f709a4cb39cde4cedab7c3be89e05f3023067 and ca4ca78b82c5d430c69ce01bf794e8886ce81431
author Matt Johnston <matt@ucc.asn.au>
date Sat, 10 Jun 2006 16:39:40 +0000
parents eed26cff980b
children 5ff8218bcee9
comparison
equal deleted inserted replaced
329:8ed0dce45126 330:5488db2e9e4e
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, [email protected], http://math.libtomcrypt.org
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 /* 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 }
78 #endif