diff --git a/core/bitarithm.c b/core/bitarithm.c index a830fdafa1..4ce7d34a2b 100644 --- a/core/bitarithm.c +++ b/core/bitarithm.c @@ -57,6 +57,17 @@ unsigned bitarithm_bits_set(unsigned v) return c; } +#if !ARCH_32_BIT +uint8_t bitarithm_bits_set_u32(uint32_t v) +{ + uint8_t c; + for (c = 0; v; c++) { + v &= v - 1; /* clear the least significant bit set */ + } + return c; +} +#endif + const uint8_t MultiplyDeBruijnBitPosition[32] = { 0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8, diff --git a/core/include/bitarithm.h b/core/include/bitarithm.h index bebdb3e405..1adc55a583 100644 --- a/core/include/bitarithm.h +++ b/core/include/bitarithm.h @@ -115,12 +115,27 @@ static inline unsigned bitarithm_lsb(unsigned v); /** * @brief Returns the number of bits set in a value - * @param[in] v Input value + * @param[in] v Input value with platform-dependent word size * @return Number of set bits * */ unsigned bitarithm_bits_set(unsigned v); +/** + * @brief Returns the (uint32_t version) number of bits set in a value + * @param[in] v Input value with 32 bit size + * @return Number of set bits + * + */ +#if ARCH_32_BIT +static inline uint8_t bitarithm_bits_set_u32(uint32_t v) +{ + return bitarithm_bits_set(v); +} +#else +uint8_t bitarithm_bits_set_u32(uint32_t v); +#endif + /* implementations */ static inline unsigned bitarithm_lsb(unsigned v) diff --git a/tests/unittests/tests-core/tests-core-bitarithm.c b/tests/unittests/tests-core/tests-core-bitarithm.c index b6584c39f9..b9ae1b5aa4 100644 --- a/tests/unittests/tests-core/tests-core-bitarithm.c +++ b/tests/unittests/tests-core/tests-core-bitarithm.c @@ -155,7 +155,8 @@ static void test_bitarithm_msb_limit(void) static void test_bitarithm_msb_random(void) { TEST_ASSERT_EQUAL_INT(4, bitarithm_msb(19)); /* randomized by fair - dice roll ;-) */ + * dice roll ;-) + */ } static void test_bitarithm_msb_16bit(void) @@ -208,7 +209,13 @@ static void test_bitarithm_bits_set_limit(void) static void test_bitarithm_bits_set_random(void) { TEST_ASSERT_EQUAL_INT(3, bitarithm_bits_set(7)); /* randomized by fair - dice roll ;-) */ + * dice roll ;-) + */ +} + +static void test_bitarithm_bits_set_u32_random(void) +{ + TEST_ASSERT_EQUAL_INT(21, bitarithm_bits_set_u32(4072524027)); /* Source: https://www.random.org/bytes */ } Test *tests_core_bitarithm_tests(void) @@ -244,6 +251,7 @@ Test *tests_core_bitarithm_tests(void) new_TestFixture(test_bitarithm_bits_set_one), new_TestFixture(test_bitarithm_bits_set_limit), new_TestFixture(test_bitarithm_bits_set_random), + new_TestFixture(test_bitarithm_bits_set_u32_random), }; EMB_UNIT_TESTCALLER(core_bitarithm_tests, NULL, NULL, fixtures);