Bitwise Right Shift

Bitwise Right Shift

Bitwise Right Shift Operator

Java supports two kinds of the bitwise right shift operators which are basically used to perform shift right operations on numbers.

  1. Signed Right Shift (>>)
  2. Unsigned Right Shift (>>>)

Signed Right Shift

The Bitwise Signed Right Shift Operator is used to shift the bits to the right of a given number number. It perform the task in three different subtasks:

  1. It first convert the number into bits.
  2. It then shifts the specified bits towards right.
  3. Finally, it convert the these bits back to the number.
Run
public class Main {
    public static void main(String[] args) {
        int x = 12;
        System.out.println("12 in binary form "+Integer.toBinaryString(x));
        int y = 2;
        int shift = x >> y;
        System.out.println("12 will become : " + shift+" in integer form");
        System.out.println("12 in binary form after performing right shift "+Integer.toBinaryString(shift));
    }
}

Output :

12 in binary form 1100
12 will become : 3 in integer form
12 in binary form after performing right shift 11
Bitwise Right Shift Diagram

Unsigned Right Shift

The Bitwise Unsigned Right Shift Operator is used to shift the bits to the right of a given number number and adds the equal number of zeros at the beginning, which means zero bits are moved in from the left while extra bits that were pushed off to the right are discarded. Since the sign bit is set to 0, the outcome is always positive.

Run

public class Main {
    public static void main(String[] args) {
        int x = -12;
        System.out.println("-12 in binary form "+Integer.toBinaryString(x));
        int y = 2;
        int shift = x >>> y;
        System.out.println("-12 will become  : " + shift+" in integer form");
        System.out.println("-12 in binary form after performing unsingned right shift "+Integer.toBinaryString(shift));
    }
}

Output :

-12 in binary form 11111111111111111111111111110100
-12 will become  : 1073741821 in integer form
-12 in binary form after performing unsingned right shift 111111111111111111111111111101

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription