Merge pull request #578 from PX4/fix_mp_prime_strong_lucas_lefridge_compilation
[libtommath.git] / mp_to_radix.c
blob1e5e67110d3d7d3f9fa6ef54b6ecc72680ba1d6c
1 #include "tommath_private.h"
2 #ifdef MP_TO_RADIX_C
3 /* LibTomMath, multiple-precision integer library -- Tom St Denis */
4 /* SPDX-License-Identifier: Unlicense */
6 /* reverse an array, used for radix code */
7 static void s_reverse(char *s, size_t len)
9 size_t ix = 0, iy = len - 1u;
10 while (ix < iy) {
11 MP_EXCH(char, s[ix], s[iy]);
12 ++ix;
13 --iy;
17 /* stores a bignum as a ASCII string in a given radix (2..64)
19 * Stores upto "size - 1" chars and always a NULL byte, puts the number of characters
20 * written, including the '\0', in "written".
22 mp_err mp_to_radix(const mp_int *a, char *str, size_t maxlen, size_t *written, int radix)
24 size_t digs;
25 mp_err err;
26 mp_int t;
27 mp_digit d;
28 char *_s = str;
30 /* check range of radix and size*/
31 if (maxlen < 2u) {
32 return MP_BUF;
34 if ((radix < 2) || (radix > 64)) {
35 return MP_VAL;
38 /* quick out if its zero */
39 if (mp_iszero(a)) {
40 *str++ = '0';
41 *str = '\0';
42 if (written != NULL) {
43 *written = 2u;
45 return MP_OKAY;
48 if ((err = mp_init_copy(&t, a)) != MP_OKAY) {
49 return err;
52 /* if it is negative output a - */
53 if (mp_isneg(&t)) {
54 /* we have to reverse our digits later... but not the - sign!! */
55 ++_s;
57 /* store the flag and mark the number as positive */
58 *str++ = '-';
59 t.sign = MP_ZPOS;
61 /* subtract a char */
62 --maxlen;
64 digs = 0u;
65 while (!mp_iszero(&t)) {
66 if (--maxlen < 1u) {
67 /* no more room */
68 err = MP_BUF;
69 goto LBL_ERR;
71 if ((err = mp_div_d(&t, (mp_digit)radix, &t, &d)) != MP_OKAY) {
72 goto LBL_ERR;
74 *str++ = s_mp_radix_map[d];
75 ++digs;
77 /* reverse the digits of the string. In this case _s points
78 * to the first digit [excluding the sign] of the number
80 s_reverse(_s, digs);
82 /* append a NULL so the string is properly terminated */
83 *str = '\0';
84 digs++;
86 if (written != NULL) {
87 *written = mp_isneg(a) ? (digs + 1u): digs;
90 LBL_ERR:
91 mp_clear(&t);
92 return err;
95 #endif