Difference Between Right Shift and Unsigned Right Shift or Zero Filled Right Shift

Share

Right Shift and Unsigned Right Shift or Zero Filled Right Shift both are Bitwise operators and work only on integer types. It works with the bits of an integer type values which is typical of 32 bits.

Difference between right shift and unsigned right shift or Zero filled right shift

RIGHT SHIFTUNSIGNED RIGHT SHIFT
It shifts all bits of a binary number to the right as per the mentioned number of timesIt shifts all bits of a binary number to the right by filling zeros at the most significant bit as per the mentioned number of times
Each time when the right shift takes place it divides the binary number by 2, ignoring the remainderIt works by filling zeros on the leftmost most side in the binary representation of an integer
It preserves the sign of negative number or sign extensionIt doesn't preserve such sign extension
Most significant bit or leftmost bit filled with previous value in order to maintain signed extension to represent the given integer in positive or negative. if it is one it is negative and if it is zero then it is positiveMost significant bit or leftmost bit filled with 0's, no matter what the initial value was. therefore, it is unsigned shift
It is declared using ">>" symbol. Syntax, num >> n_timesIt is declared using ">>" symbol. Syntax, num >>> n_times
It is used to represent a numeric valueIt can be used in many situations such as at the time when we work with pixel-based values

Java program to show the working of right shift and unsigned right shift

public class BitwiseOperatorExample {
    public static void main(String[] args) {
        int val = -3;
        int result;
        System.out.println("Input = " + val);
        result = val >> 2;
        System.out.println("Right Shift = " + result);
        result = val >>> 2;
        System.out.println("Unsigned Right Shift = " + result);
    }
}

Output:

Input = -3
Right Shift = -1
Unsigned Right Shift = 1073741823

 

Working of Right Shift and Unsigned Right Shift With Same Input

Right Shift

Unsigned right shift or Zero filled right shift

This post was last modified on August 17, 2022

Sandeep Verma

Published by
Sandeep Verma
Tags: bitwise operator java right shift unsigned right shift