Possible Duplicate:
Best algorithm to count the number of set bits in a 32-bit integer?
Given a 32bit unsigned integer, we want to count the number of non-zero bits in its binary representation. What is the fastest way to do that ?
We want to do this N~10^10 times.
note: using a large look up table is usually not a good idea because of the architecture of current cpu’s . it is much faster to calculate it locally than to use a huge array that needs looking at the external memory
There are actually several options, I presume the native way is way too slow for this.
You can go with lookup table for 8-bit value and do it in parallel for all four bytes from unsigned int value, then sum the result. This one could be also quite well-paralelizable (be it multi-core, or maybe even some SSE3/4 could help).
You can also go with Brian Kernighan’s solution:
And the last possible way I found somewhere some time ago is (on 64-bit machines, as the modulo operation would be really fast there):