Search code examples
cassemblybit-manipulationbitmask

Count bits in the number


Duplicate:

Best algorithm to count the number of set bits in a 32-bit integer?


Suppose you have a number. Is there any way to count the bits which equals to 1 in binary representation of that number, not using iteration? I mean, is there any way to do it in constant time using some bitwise operators and masks. I need solution which will work well for both architectures 32 bit and 64 bit. Ah almost forgot, I need it for C language or assembler is also good.


Solution

  • There is a bit counting algorithm without a loop at http://graphics.stanford.edu/~seander/bithacks.html. Lots of bit counting algorithms at http://gurmeetsingh.wordpress.com/2008/08/05/fast-bit-counting-routines/