Search code examples
cbit-manipulationbitwise-operatorsbit-shiftbitwise-and

Bitwise operations (shifting return values)


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)


Solution

  • 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.