From 85cb0b4f2ca8145d3c8495f738d812ee9cfab899 Mon Sep 17 00:00:00 2001 From: Saleem Rashid Date: Thu, 27 Jul 2017 19:25:00 +0100 Subject: [PATCH] bignum: Fix bn_digitcount bn_digitcount used to use bn_bitcount. This would give the maximum digits, which would often be higher than the actual number. This would result in leading zeroes in bn_format. --- bignum.c | 25 +++++++++++++++++++++++++ bignum.h | 11 +---------- 2 files changed, 26 insertions(+), 10 deletions(-) diff --git a/bignum.c b/bignum.c index caca7b6078..d0e2b28256 100644 --- a/bignum.c +++ b/bignum.c @@ -195,6 +195,31 @@ int bn_bitcount(const bignum256 *a) return 0; } +#define DIGITS 78 // log10(2 ^ 256) + +unsigned int bn_digitcount(const bignum256 *a) +{ + bignum256 val; + memcpy(&val, a, sizeof(bignum256)); + + unsigned int digits = 1; + + for (unsigned int i = 0; i < DIGITS; i += 3) { + uint32_t limb; + bn_divmod1000(&val, &limb); + + if (limb >= 100) { + digits = i + 3; + } else if (limb >= 10) { + digits = i + 2; + } else if (limb >= 1) { + digits = i + 1; + } + } + + return digits; +} + // sets a bignum to zero. void bn_zero(bignum256 *a) { diff --git a/bignum.h b/bignum.h index ec64094f32..f96cad6654 100644 --- a/bignum.h +++ b/bignum.h @@ -83,16 +83,7 @@ static inline void bn_copy(const bignum256 *a, bignum256 *b) { int bn_bitcount(const bignum256 *a); -static inline int bn_digitcount(const bignum256 *a) -{ - int bitcount = bn_bitcount(a); - - if (bitcount == 256) { - return 78; - } else { - return bitcount * 78 / 256 + 1; - } -} +unsigned int bn_digitcount(const bignum256 *a); void bn_zero(bignum256 *a);