Here's a fast way to count the number of bits in an integer. It uses a 4 bit wide lookup table and interates through each nibble to add to the total number of bits set.
Code:
int bitcount(unsigned int num)
{
int count = 0;
static int nibblebits[] =
{0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4};
for(; num != 0; num >>= 4)
count += nibblebits[num & 0x0f];
return count;
}
Extensions:
Sources:
http://c-faq.com/misc/bitcount.html
Comments (0)
You don't have permission to comment on this page.