Bitwise Right Shift operators in Java

Description

Java supports following two right shift operators.

1)>>(Signed right shift) In Java, the operator ‘>>’ is signed right shift operator. All integers are
signed in Java, and it is fine to use >> for negative numbers. The operator ‘>>’ uses the sign bit (left
most bit) to fill the trailing position after shift. If the number is negative, then 1 is used as a filler and if
the number is positive, then 0 is used as filler. For example, if binary representation of number is
10…100, then right shifting it by 2 using >> will make it 11…1.
See following example…


class Test
{
public static void main(String args[]) {
int x = -4;
System.out.print("x = ");
System.out.println(x>>1);
int y = 4;
System.out.print("y = ");
System.out.println(y>>1);
}
}

2)>>>(UnSigned right shift) In Java operator ‘>>>’ is unsigned shift operator. It always fills 0 irrespective of sign of the number.


class Test {
public static void main(String args[]) {

// x is stored using 32 bit 2's complement form.
// Binary representation of -1 is all 1s (111..1)
int x = -1;

System.out.print("x>>>29 = ");
System.out.println(x>>>29); // The value of 'x>>>29' is 00...0111
System.out.print("x>>>30 = ");
System.out.println(x>>>30); // The value of 'x>>>30' is 00...0011
System.out.print("x>>>31 = ");
System.out.println(x>>>31); // The value of 'x>>>31' is 00...0001
}
}

Author Description

humanz

Our mission is to bring the affordable Technology education to people everywhere, in order to help them achieve their dreams and change the world. - Follow @program_guide

No comments yet.

Join the Conversation