Skip to content
Snippets Groups Projects
Commit 0ecaaf02 authored by Peter Kietzmann's avatar Peter Kietzmann
Browse files

core/bitarithm: add explicit 32-bit function

parent 6bfd3338
No related branches found
No related tags found
No related merge requests found
......@@ -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,
......
......@@ -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)
......
......@@ -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);
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment