What is (x & 1) and (x >>= 1)?

Sandra K picture Sandra K · Aug 12, 2016 · Viewed 103.9k times · Source

I am trying to do assignment: "Find the number of bits in an unsigned integer data type without using the sizeof() function."

And my design is to convert the integer to bits and then to count them. For ex: 10 is 1010 and 5 is 101

Converting integer to a bit representation shows something like this:

do
{ 
    Vec.push_back( x & 1 ) 
} 
while ( x >>= 1 );

I don't want to just copy paste stuff. When I use F-10 I see what (x & 1) is doing but I don't know it is name or how it does its job(compare something?). Also I know >= which "greater than or equal" but what is x >>= 1?

Note: The marked duplicate is a JavaScript and not C++

Answer

Sergey Kalinichenko picture Sergey Kalinichenko · Aug 12, 2016

These are Bitwise Operators (reference).

x & 1 produces a value that is either 1 or 0, depending on the least significant bit of x: if the last bit is 1, the result of x & 1 is 1; otherwise, it is 0. This is a bitwise AND operation.

x >>= 1 means "set x to itself shifted by one bit to the right". The expression evaluates to the new value of x after the shift.

Note: The value of the most significant bit after the shift is zero for values of unsigned type. For values of signed type the most significant bit is copied from the sign bit of the value prior to shifting as part of sign extension, so the loop will never finish if x is a signed type, and the initial value is negative.