Nope Nope - 3 months ago 20
C++ Question

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

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
?

Answer

These are Bitwise Operators (reference).

x & 1 produces an int that is either 1 or 0, depending on the last 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 value prior to shifting, so the loop will never finish if x is a signed type, and the initial value is negative.