Bitwise operations (shifting return values)

178 Views Asked by At

if (((number >> i) & 1) == 1)

this is my code example.

How is the return value determined in this operation? We shift numbers to the right or left. what is the return value?

if (((number >> i) & 1) == 1)

3

There are 3 best solutions below

0
John Bode On BEST ANSWER

number >> i bitwise-shifts number to the right by i bits:

  number   i    number >> i
  ------   -    -----------
01010101   1    00101010
01010101   2    00010101
01010101   3    00001010

etc.

(number >> i) & 1 does a bitwise-AND of number >> 1 against 1:

  00101010 (01010101 >> 1)
& 00000001
----------
  00000000

  00010101 (01010101 >> 2)
& 00000001
----------
  00000001

So basically,

if (((number >> i) & 1) == 1)

will branch if the low bit of the shifted value is set.

0
Vlad from Moscow On

How is the return value determined in this operation?

There is no return value. There is an if statement with the equality operator

if (((number >> i) & 1) == 1)

The result of the equality operator is value 0 or 1 of the type int dependent on whether two operands, ((number >> i) & 1) and 1, of the expression are unequal or equal to each other correspondingly. If the result is 1 (operands are equal each other) then the sub-statement of the if statement will get the control.

So the of statements checks whether the i-th bit of number is set to 1 or to 0.

1
user6099871 On

>> is a right-shift operator in C language.

It depends on three factors that the result of ((number >> i) & 1) would be.

  1. The type of the number is either signed or unsigned.
  2. The total size in bit of the number, i.e. 8*sizeof(number).
  3. The value of i.
number is signed number is unsigned
The value of i >= The total size in bit of the number the signed bit of number 0
The value of i < The total size in bit of the number the i-th bit of number (LSb is 0-th bit) the i-th bit of number (LSb is 0-th bit)