Possible Duplicate:
Best algorithm to count the number of set bits in a 32-bit integer?
Counting the number of bits that are set
How to find the number of bits set in an unsigned integer when it is allowed to iterate the loop same number of times as the number of bits set (if 3 bits are set, you can iterate the loop only 3 times)
This is a method I know of for doing this, it will only iterate for the number of bits set in
v, at the end of executioncwill hold the number of bits inv:source: C Programming Language 2nd Ed. (by Brian W. Kernighan and Dennis M. Ritchie)
example: