Search code examples
c++bit-manipulationbitset

What is the fastest way to count all set bits?


What is the fastest way to count all set bits?
The number from which I am counting bits is from 1<=n<2^63, only positive values.

For now I use bitset from the library and it is pretty fast, but if there is any faster option I would like to know.

In the worst case scenario I have over 1 billion iterations, so I am looking a way to speed it up.
This is the part of my loop where I am counting the setted bits:

if (std::bitset<64>(currentNumber).count() == numofOnes)
++counter;

Solution

  • Here is a demo of what I mean with a balanced lookup table.
    This one is heavy on the size saving.
    You can adapt the concept to lookup tables of size e.g. 64 or 256, speeding up considerably.

    #include <iostream>
    
    using namespace std;
    
    int main()
    {
       unsigned long long int input=679043ULL; // just a big number, for demo
       
       unsigned char lookup[16]={0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4};
       unsigned char result=0;
    
       while (input>0)
       {
           cout << (unsigned int) result << " " << (input&15) << " " << input << endl;
           result+=lookup[input&15];
           input>>=4;
       }
       cout << (unsigned int)result << endl;
       return 0;
    }
    

    Output:

    0 3 679043
    2 8 42440
    3 12 2652
    5 5 165
    7 10 10
    9
    

    The demo outputs shows that the loop accumulates
    2 bits in "3",
    1 bit in "8",
    2 bits in "12",
    2 bits in "5",
    two bits in "10";
    for a total of 9.