How Shift Operator Works?

Shift Operator can be said bitwise operator because shift operators also converts each digit in binary digits and shift bits left or right and adds 0 according to its operators.

We have shift left << and shift right >> operators for these operations.

  • Left shift operator shifts all bits towards left by certain number of specified bits
  • Right shift operator shifts all bits towards right by certain number of specified bits.


Examples

Shift Left

5 << 2
Converting each digits in binary:
    5 = 0101

Now,
      0101 << 2 = 010100 
      (add 2 bits from right)

      010100 = 20

That means,
    5 << 2 = 20
It is also same as (a * 2 ^ b).

Shift Right
5 >> 2
Converting each digits in binary:
    5 = 0101

Now,
      0101 >> 2 = 01 
      (remove 2 bits from left)

      01 = 1

That means,
    5 >> 2 = 1
It is also same as (a / 2 ^ b).