1 #include "tommath_private.h"
2 #ifdef BN_MP_TO_RADIX_C
3 /* LibTomMath, multiple-precision integer library -- Tom St Denis */
4 /* SPDX-License-Identifier: Unlicense */
6 /* stores a bignum as a ASCII string in a given radix (2..64)
8 * Stores upto "size - 1" chars and always a NULL byte, puts the number of characters
9 * written, including the '\0', in "written".
11 mp_err
mp_to_radix(const mp_int
*a
, char *str
, size_t maxlen
, size_t *written
, int radix
)
19 /* check range of radix and size*/
23 if ((radix
< 2) || (radix
> 64)) {
27 /* quick out if its zero */
31 if (written
!= NULL
) {
37 if ((err
= mp_init_copy(&t
, a
)) != MP_OKAY
) {
41 /* if it is negative output a - */
42 if (t
.sign
== MP_NEG
) {
43 /* we have to reverse our digits later... but not the - sign!! */
46 /* store the flag and mark the number as positive */
54 while (!MP_IS_ZERO(&t
)) {
60 if ((err
= mp_div_d(&t
, (mp_digit
)radix
, &t
, &d
)) != MP_OKAY
) {
63 *str
++ = mp_s_rmap
[d
];
66 /* reverse the digits of the string. In this case _s points
67 * to the first digit [exluding the sign] of the number
69 s_mp_reverse((unsigned char *)_s
, digs
);
71 /* append a NULL so the string is properly terminated */
75 if (written
!= NULL
) {
76 *written
= (a
->sign
== MP_NEG
) ? (digs
+ 1u): digs
;