How to implement Bitcount using only Bitwise operators?

Viewed 45666

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.

4 Answers
Related