Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

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

like image 292
Sandra K Avatar asked Aug 12 '16 16:08

Sandra K


People also ask

What is X value?

Multiplicand × Multiplier = Product. Let us take Multipler as x, Multiplicand × x = Product. Then the formula to find the value of x is. X = product / Multiplicand.

What is IXI in math?

i x i = -1, -1 x i = -i, -i x i = 1, 1 x i = i. We can also call this cycle as imaginary numbers chart as the cycle continues through the exponents. This knowledge of the exponential qualities of imaginary numbers.

What is the X variable?

An independent variable is a variable that represents a quantity that is being manipulated in an experiment. x is often the variable used to represent the independent variable in an equation.


2 Answers

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.

like image 155
Sergey Kalinichenko Avatar answered Oct 13 '22 17:10

Sergey Kalinichenko


x & 1 is equivalent to x % 2.

x >> 1 is equivalent to x / 2

So, these things are basically the result and remainder of divide by two.

like image 53
rama Avatar answered Oct 13 '22 18:10

rama