Left Shift (<<) and Right Shift (>>) Operators

What is Left Shift (<<) Operator:

  1. a<<b means left shift the bits of number a by b places.
  2. 3<<2 means left shift the bits of number 3 by 2 places. Result = 12
    1. 011 is the bit representation of number 3.
    2. Left shift all the bits so => 0 1 1 0 (number =6)
    3. Left shift all the bits so => 0 1 1 0 0 (number = 12).
  3. Each time you left shift the number, it will be multiplied by 2. So if you shift by a number by k then number will be multiplied by k2.

What is Right Shift (>>) Operator:

  • a>>b means right shift the bits of number a by b places.
  • 12>>2 means right shift the bits of number 12 by 2 places. Result = 3
    1. 0 1 1 0 0 is the bit representation of number 12.
    2. Right shift all the bits so => 0 1 1 0 (number =6)
    3. Right shift all the bits so => 0 1 1 (number = 3).
  • Each time you right shift the number, it will be divided by 2. So if you shift by a number by k then number will be divided by k2. (Keeps only integer).

Java Code:



Output:

n<<1, Left shift by 1 of n: 10 is : 20
n>>1, Right shift by 1 of n: 10 is : 5
n<<1, Left shift by 1 of n: 62 is : 124
n>>1, Right shift by 1 of n: 62 is : 31

__________________________________________________
Top Companies Interview Questions..-

Google Microsoft Amazon Facebook more..

If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.
__________________________________________________

%d bloggers like this: