| 
  • If you are citizen of an European Union member nation, you may not use this service unless you are at least 16 years old.

  • You already know Dokkio is an AI-powered assistant to organize & manage your digital files & messages. Very soon, Dokkio will support Outlook as well as One Drive. Check it out today!

View
 

CountBits

This version was saved 15 years, 11 months ago View current version     Page history
Saved by Kenneth Finnegan
on May 9, 2008 at 8:36:45 pm
 

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.