Java Bitwise Operators Unsigned Right Shift

Introduction

The >> operator fills the high-order bit with its previous contents.

This preserves the sign of the value.

To shift a zero into the high-order bit no matter what its initial value was, use Unsigned Right Shift.

Java's unsigned, shift-right operator >>> always shifts zeros into the high-order bit.

For example, a is set to -1, which sets all 32 bits to 1 in binary.

This value is shifted right 24 bits, filling the top 24 bits with zeros, ignoring normal sign extension.

This sets a to 255.

int a = -1;  
a = a >>> 24; 

Here is the same operation in binary form: 
11111111 11111111 11111111 11111111    -1 in binary as an int 
>>>24 
00000000 00000000 00000000 11111111   255 in binary as an int 

byte and short values are promoted to int in expressions.

The sign-shift occurs and the shift will take place on a 32-bit rather than on an 8- or 16-bit value.

public class Main {
  static public void main(String args[]) {
    int a = -1;  
    a = a >>> 24; //from   w  w w.  ja  v  a  2s  .  c  om
    System.out.println(a);

  }
}



PreviousNext

Related