libtommath/mp_radix_size.c

35 lines
769 B
C
Raw Normal View History

#include "tommath_private.h"
#ifdef MP_RADIX_SIZE_C
2019-04-07 13:29:11 +00:00
/* LibTomMath, multiple-precision integer library -- Tom St Denis */
/* SPDX-License-Identifier: Unlicense */
2003-08-05 01:24:44 +00:00
/* returns size of ASCII representation */
2019-10-21 17:12:22 +00:00
mp_err mp_radix_size(const mp_int *a, int radix, size_t *size)
2003-08-05 01:24:44 +00:00
{
2019-10-10 22:29:20 +00:00
mp_err err;
mp_int a_;
int b;
2004-01-25 17:40:21 +00:00
2017-08-30 17:13:53 +00:00
/* make sure the radix is in range */
if ((radix < 2) || (radix > 64)) {
return MP_VAL;
}
2003-08-05 01:24:44 +00:00
2019-10-24 15:43:31 +00:00
if (mp_iszero(a)) {
2017-08-30 17:13:53 +00:00
*size = 2;
return MP_OKAY;
}
2003-08-05 01:24:44 +00:00
2019-10-10 22:29:20 +00:00
a_ = *a;
a_.sign = MP_ZPOS;
if ((err = mp_log_n(&a_, radix, &b)) != MP_OKAY) {
return err;
2017-08-30 17:13:53 +00:00
}
2005-03-12 11:55:11 +00:00
2019-10-10 22:29:20 +00:00
/* mp_ilogb truncates to zero, hence we need one extra put on top and one for `\0`. */
*size = (size_t)b + 2U + (mp_isneg(a) ? 1U : 0U);
2019-05-29 10:23:08 +00:00
return MP_OKAY;
2003-08-05 01:24:44 +00:00
}
2004-10-29 22:07:18 +00:00
#endif