]> pd.if.org Git - zpackage/blob - tomsfastmath/src/bin/fp_toradix_n.c
commit files needed for zpm-fetchurl
[zpackage] / tomsfastmath / src / bin / fp_toradix_n.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_toradix_n(fp_int *a, char *str, int radix, int maxlen)
13 {
14    int digs;
15    fp_int t;
16    fp_digit d;
17    char *_s = str;
18
19    /* check range of the radix */
20    if (maxlen < 2 || radix < 2 || radix > 64)
21       return FP_VAL;
22
23    /* quick check for zero */
24    if (fp_iszero(a) == FP_YES) {
25       *str++ = '0';
26       *str = '\0';
27       return FP_OKAY;
28    }
29
30    fp_init_copy(&t, a);
31
32    /* if it is negative output a - */
33    if (t.sign == FP_NEG) {
34       /* we have to reverse our digits later... but not the - sign!! */
35       ++_s;
36
37       /* store the flag and mark the number as positive */
38       *str++ = '-';
39       t.sign = FP_ZPOS;
40
41       /* subtract a char */
42       --maxlen;
43    }
44
45    digs = 0;
46    while (fp_iszero (&t) == FP_NO) {
47       if (--maxlen < 1) {
48          /* no more room */
49          break;
50       }
51       fp_div_d(&t, (fp_digit) radix, &t, &d);
52       *str++ = fp_s_rmap[d];
53       ++digs;
54    }
55
56    /* reverse the digits of the string.  In this case _s points
57     * to the first digit [exluding the sign] of the number]
58     */
59    fp_reverse((unsigned char *) _s, digs);
60
61    /* append a NULL so the string is properly terminated */
62    *str = '\0';
63
64    if (maxlen < 1)
65       return FP_VAL;
66    return FP_OKAY;
67 }
68
69 /* $Source$ */
70 /* $Revision$ */
71 /* $Date$ */