1
0
mirror of https://github.com/RIOT-OS/RIOT.git synced 2024-12-29 04:50:03 +01:00

sys/bitfield: add bf_popcnt()

This commit is contained in:
Benjamin Valentin 2022-11-10 23:40:03 +01:00 committed by Benjamin Valentin
parent e402e3f57a
commit 4dd0594d09
2 changed files with 29 additions and 0 deletions

View File

@ -21,6 +21,7 @@
#include <stdint.h>
#include <string.h>
#include "bitfield.h"
#include "bitarithm.h"
#include "irq.h"
static inline unsigned _skip_bytes(const uint8_t field[], unsigned nbytes, uint8_t byte)
@ -92,3 +93,21 @@ void bf_set_all(uint8_t field[], size_t size)
field[bytes] = ~((1U << (8 - bits)) - 1);
}
}
unsigned bf_popcnt(const uint8_t field[], size_t size)
{
unsigned bytes = size >> 3;
unsigned bits = size & 0x7;
unsigned mask = ~((1U << (8 - bits)) - 1);
unsigned count = 0;
for (unsigned i = 0; i < bytes; ++i) {
count += bitarithm_bits_set(field[i]);
}
if (bits) {
count += bitarithm_bits_set(field[bytes] & mask);
}
return count;
}

View File

@ -219,6 +219,16 @@ int bf_find_first_unset(const uint8_t field[], size_t size);
*/
void bf_set_all(uint8_t field[], size_t size);
/**
* @brief Count set bits in the bitfield
*
* @param[in] field The bitfield
* @param[in] size The size of the bitfield
*
* @return number of '1' bits in the bitfield
*/
unsigned bf_popcnt(const uint8_t field[], size_t size);
#ifdef __cplusplus
}
#endif