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.
Only Bitwise ops are allowed. No “if”, “for” etc
int x = 4;
printf("%d\n", x & 0x1);
printf("%d\n", (x >> 1) & 0x1);
printf("%d\n", (x >> 2) & 0x1);
printf("%d\n", (x >> 3) & 0x1);
Thank you.
From http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
Edit: Admittedly it’s a bit optimized which makes it harder to read. It’s easier to read as:
Each step of those five, adds neighbouring bits together in groups of 1, then 2, then 4 etc.
The method is based in divide and conquer.
In the first step we add together bits 0 and 1 and put the result in the two bit segment 0-1, add bits 2 and 3 and put the result in the two-bit segment 2-3 etc…
In the second step we add the two-bits 0-1 and 2-3 together and put the result in four-bit 0-3, add together two-bits 4-5 and 6-7 and put the result in four-bit 4-7 etc…
Example:
which is equal to 5, which is the correct result