The task is to implement a bit count logic using only bitwise operators. I got it working fine, but am wondering if someone can suggest a more elegant approach.
Onl
I would use a pre-computed array
uint8_t set_bits_in_byte_table[ 256 ];
The i-th entry in this table stores the number of set bits in byte i, e.g. set_bits_in_byte_table[ 100 ] = 3 since there are 3 1 bits in binary representation of decimal 100 (=0x64 = 0110-0100).
Then I would try
size_t count_set_bits( uint32_t const x ) {
size_t count = 0;
uint8_t const * byte_ptr = (uint8_t const *) &x;
count += set_bits_in_byte_table[ *byte_ptr++ ];
count += set_bits_in_byte_table[ *byte_ptr++ ];
count += set_bits_in_byte_table[ *byte_ptr++ ];
count += set_bits_in_byte_table[ *byte_ptr++ ];
return count;
}