1 #include "tommath_private.h"
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;
11 MP_EXCH(char, s
[ix
], s
[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
)
30 /* check range of radix and size*/
34 if ((radix
< 2) || (radix
> 64)) {
38 /* quick out if its zero */
42 if (written
!= NULL
) {
48 if ((err
= mp_init_copy(&t
, a
)) != MP_OKAY
) {
52 /* if it is negative output a - */
54 /* we have to reverse our digits later... but not the - sign!! */
57 /* store the flag and mark the number as positive */
65 while (!mp_iszero(&t
)) {
71 if ((err
= mp_div_d(&t
, (mp_digit
)radix
, &t
, &d
)) != MP_OKAY
) {
74 *str
++ = s_mp_radix_map
[d
];
77 /* reverse the digits of the string. In this case _s points
78 * to the first digit [excluding the sign] of the number
82 /* append a NULL so the string is properly terminated */
86 if (written
!= NULL
) {
87 *written
= mp_isneg(a
) ? (digs
+ 1u): digs
;