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:

public class LeftRightShift {
static void LeftShift(int n){
int x = n<<1;
System.out.println("n<<1, Left shift by 1 of n: "+ n + " is : " + x);
}
static void RightShift(int n){
int x = n>>1;
System.out.println("n>>1, Right shift by 1 of n: "+ n + " is : " + x);
}
public static void main(String[] args) {
int n = 10;
LeftShift(n);
RightShift(n);
n = 62;
LeftShift(n);
RightShift(n);
}
}

view raw
LeftRightShift.java
hosted with ❤ by GitHub


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

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.