I do have an 8-bit unsigned integer and I'd like to know how many of its bits are set to 1. There is a trivial way by AND-ing (&) it with 0x01, 0x02, 0x04, 0x08, 0x0F, 0x10, 0x20, 0x40, 0x80, 0xF0 and incrementing a variable for each one of those which is not zero, but I'd like to hear more sophisticated solutions.
Asked
Active
Viewed 1,352 times
1
-
1You can use a loop and the bit shift operator. – πάντα ῥεῖ Apr 10 '15 at 15:29
-
Besides @Barry's answer, here some fun methods: http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetNaive – Daniel Frey Apr 10 '15 at 15:31
2 Answers
2
You can use a while loop with bitshifting:
uint8_t someInt = 13;
int num_ones = 0;
while (someInt)
{
num_ones += someInt & 1;
someInt = someInt >> 1;
}

dwcanillas
- 3,562
- 2
- 24
- 33