mirror of
https://github.com/trezor/trezor-firmware.git
synced 2024-11-25 00:48:19 +00:00
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.
This commit is contained in:
parent
43ea1392f2
commit
85cb0b4f2c
25
bignum.c
25
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)
|
||||
{
|
||||
|
11
bignum.h
11
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);
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user