From 558bc429ec308dd9cac314810d1b2219b4f85863 Mon Sep 17 00:00:00 2001 From: Saleem Rashid Date: Wed, 26 Jul 2017 11:32:48 +0100 Subject: [PATCH] bignum: Add bn_digitcount --- bignum.h | 11 +++++++++++ test_check.c | 31 +++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/bignum.h b/bignum.h index 8e23ab9760..7ba6204eed 100644 --- a/bignum.h +++ b/bignum.h @@ -81,6 +81,17 @@ 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; + } +} + void bn_zero(bignum256 *a); int bn_is_zero(const bignum256 *a); diff --git a/test_check.c b/test_check.c index 9dde969263..e81ddba156 100644 --- a/test_check.c +++ b/test_check.c @@ -350,6 +350,36 @@ START_TEST(test_bignum_bitcount) } END_TEST +START_TEST(test_bignum_digitcount) +{ + bignum256 a; + + bn_zero(&a); + ck_assert_int_eq(bn_digitcount(&a), 1); + + bn_one(&a); + ck_assert_int_eq(bn_digitcount(&a), 1); + + bn_read_uint32(10, &a); + ck_assert_int_eq(bn_digitcount(&a), 2); + + bn_read_uint32(11, &a); + ck_assert_int_eq(bn_digitcount(&a), 2); + + bn_read_uint32(100, &a); + ck_assert_int_eq(bn_digitcount(&a), 3); + + bn_read_uint32(0x3fffffff, &a); + ck_assert_int_eq(bn_digitcount(&a), 10); + + bn_read_uint32(0xffffffff, &a); + ck_assert_int_eq(bn_digitcount(&a), 10); + + bn_read_be(fromhex("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"), &a); + ck_assert_int_eq(bn_digitcount(&a), 78); +} +END_TEST + START_TEST(test_bignum_is_less) { bignum256 a; @@ -3193,6 +3223,7 @@ Suite *test_suite(void) tcase_add_test(tc, test_bignum_is_even); tcase_add_test(tc, test_bignum_is_odd); tcase_add_test(tc, test_bignum_bitcount); + tcase_add_test(tc, test_bignum_digitcount); tcase_add_test(tc, test_bignum_is_less); tcase_add_test(tc, test_bignum_format); suite_add_tcase(s, tc);