views:

1382

answers:

3

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.

+2  A: 

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/

pts
+1  A: 

Yes, you can do that by using a look up table.

arul
+1  A: 

Well, of course there is, but you're not going to like it.

You could, of course, build a lookup table with all the correct values in it:

table[1] = 1, table[2] = 1, table[3] = 2, etc.

So, this would give you a really fast answer, but it's a completely useless solution by itself, since the table would have to be very, very large.

You could optimize this a bit, but it requires just a little iteration. Simply create an 8-bit version of the table solution, a mere 256-entry table, then iterate over each BYTE in the value to be checked, summing the results of the table lookup. Something like:

short int tableLookup[256] = { 0, 1, 1, 2, 1, ... };
unsigned int valueToCheck = 89392491;
int result = 0;
while ( valueToCheck != 0 ) {
   result += tableLookup[ (valueToCheck & 0xFF) ];
   valueToCheck >>= 8;
}
// result should now have the correct bit count, if the table is correct.

Hmm, seems this is well known (and here I was doing this off the top of my head): http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetNaive

Bill James
Bill, there are some slicker ways to do it; follow the link to the dup.
Charlie Martin
Clear answer but you probably want unsigned int valueToCheck otherwise the right shift is arithmetic and would preserve the sign bit which will prevent the loop from terminating. If valueToCheck is a bignum of some kind, you want to use a logical right shift to do this.
RBerteig
Sure, sure, there're bound to be other ways to do it. @RBerteig, you're probably right, it's been a while since I had to deal with C's ambiguous shifting.
Bill James