Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop bit by bit over a long long in C++

Tags:

c++

long-long

bit

If I have long long x; in c++, how can I loop over each bit in the number to check if it zero or 1?

I would like to count the number of ones in the bits.

like image 221
Mohamed Naguib Avatar asked Nov 18 '13 18:11

Mohamed Naguib


2 Answers

You need to use shifting >> operator:

unsigned long long x = static_cast<unsigned long long>(your_value);
//unsigned long long fix for issue pointed out by @Zac Howland in comments
unsigned int count = 0;//number of 1 bits
while (x != 0)
{
    unsigned long long bit = x & 1;
    if( bit == 1 )
    {
        count ++;//...
    }
    else //zero
    {
        //...
    }
    x >>= 1;
}

There are other methods that do this in various ways, you can find them here (along with other stuff)

like image 165
Raxvan Avatar answered Oct 30 '22 11:10

Raxvan


You need not to do the shift operation.:)

size_t count = 0;

for ( long long v = x; v; v &= v - 1 ) ++count;
like image 22
Vlad from Moscow Avatar answered Oct 30 '22 10:10

Vlad from Moscow