]> pd.if.org Git - zpackage/blob - tomsfastmath/src/bin/fp_read_radix.c
commit files needed for zpm-fetchurl
[zpackage] / tomsfastmath / src / bin / fp_read_radix.c
1 /* TomsFastMath, a fast ISO C bignum library.
2  *
3  * This project is meant to fill in where LibTomMath
4  * falls short.  That is speed ;-)
5  *
6  * This project is public domain and free for all purposes.
7  *
8  * Tom St Denis, tomstdenis@gmail.com
9  */
10 #include <tfm_private.h>
11
12 int fp_read_radix(fp_int *a, const char *str, int radix)
13 {
14   int     y, neg;
15   char    ch;
16
17   /* set the integer to the default of zero */
18   fp_zero (a);
19
20   /* make sure the radix is ok */
21   if (radix < 2 || radix > 64) {
22     return FP_VAL;
23   }
24
25   /* if the leading digit is a
26    * minus set the sign to negative.
27    */
28   if (*str == '-') {
29     ++str;
30     neg = FP_NEG;
31   } else {
32     neg = FP_ZPOS;
33   }
34
35   /* process each digit of the string */
36   while (*str) {
37     /* if the radix < 36 the conversion is case insensitive
38      * this allows numbers like 1AB and 1ab to represent the same  value
39      * [e.g. in hex]
40      */
41     ch = (char) ((radix <= 36) ? toupper ((int)*str) : *str);
42     for (y = 0; y < 64; y++) {
43       if (ch == fp_s_rmap[y]) {
44          break;
45       }
46     }
47
48     /* if the char was found in the map
49      * and is less than the given radix add it
50      * to the number, otherwise exit the loop.
51      */
52     if (y < radix) {
53       fp_mul_d (a, (fp_digit) radix, a);
54       fp_add_d (a, (fp_digit) y, a);
55     } else {
56       break;
57     }
58     ++str;
59   }
60
61   /* set the sign only if a != 0 */
62   if (fp_iszero(a) != FP_YES) {
63      a->sign = neg;
64   }
65   return FP_OKAY;
66 }
67
68 /* $Source$ */
69 /* $Revision$ */
70 /* $Date$ */