1 /* LibTomMath, multiple-precision integer library -- Tom St Denis
3 * LibTomMath is library that provides for multiple-precision
4 * integer arithmetic as well as number theoretic functionality.
6 * The library is designed directly after the MPI library by
7 * Michael Fromberger but has been written from scratch with
8 * additional optimizations in place.
10 * The library is free for all purposes without any express
13 * Tom St Denis, tomstdenis@iahu.ca, http://math.libtomcrypt.org
17 /* chars used in radix conversions */
18 static const char *s_rmap = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+/";
20 /* read a string [ASCII] in a given radix */
22 mp_read_radix (mp_int * a, char *str, int radix)
27 if (radix < 2 || radix > 64) {
40 ch = (char) ((radix < 36) ? toupper (*str) : *str);
41 for (y = 0; y < 64; y++) {
42 if (ch == s_rmap[y]) {
48 if ((res = mp_mul_d (a, (mp_digit) radix, a)) != MP_OKAY) {
51 if ((res = mp_add_d (a, (mp_digit) y, a)) != MP_OKAY) {
59 if (mp_iszero(a) != 1) {
65 /* stores a bignum as a ASCII string in a given radix (2..64) */
67 mp_toradix (mp_int * a, char *str, int radix)
74 if (radix < 2 || radix > 64) {
78 /* quick out if its zero */
79 if (mp_iszero(a) == 1) {
86 if ((res = mp_init_copy (&t, a)) != MP_OKAY) {
90 if (t.sign == MP_NEG) {
97 while (mp_iszero (&t) == 0) {
98 if ((res = mp_div_d (&t, (mp_digit) radix, &t, &d)) != MP_OKAY) {
105 bn_reverse ((unsigned char *)_s, digs);
111 /* returns size of ASCII reprensentation */
113 mp_radix_size (mp_int * a, int radix)
119 /* special case for binary */
121 return mp_count_bits (a) + (a->sign == MP_NEG ? 1 : 0) + 1;
124 if (radix < 2 || radix > 64) {
128 if ((res = mp_init_copy (&t, a)) != MP_OKAY) {
133 if (t.sign == MP_NEG) {
138 while (mp_iszero (&t) == 0) {
139 if ((res = mp_div_d (&t, (mp_digit) radix, &t, &d)) != MP_OKAY) {
149 /* read a bigint from a file stream in ASCII */
150 int mp_fread(mp_int *a, int radix, FILE *stream)
157 /* if first digit is - then set negative */
167 /* find y in the radix map */
168 for (y = 0; y < radix; y++) {
169 if (s_rmap[y] == ch) {
177 /* shift up and add */
178 if ((err = mp_mul_d(a, radix, a)) != MP_OKAY) {
181 if ((err = mp_add_d(a, y, a)) != MP_OKAY) {
187 if (mp_cmp_d(a, 0) != MP_EQ) {
194 int mp_fwrite(mp_int *a, int radix, FILE *stream)
199 len = mp_radix_size(a, radix);
209 if ((err = mp_toradix(a, buf, radix)) != MP_OKAY) {
214 for (x = 0; x < len; x++) {
215 if (fputc(buf[x], stream) == EOF) {