Wednesday, September 22, 2010

Unsigned right shift operator

The signed right shift >> uses sign extension: If the value is positive, zeroes are inserted at the higher-order bits; if the value is negative, ones are inserted at the higher-order bits. Java has also added the unsigned right shift >>>, which uses zero extension: Regardless of the sign, zeroes are inserted at the higher-order bits. This operator does not exist in C or C++.

If you shift a char, byte, or short, it will be promoted to int before the shift takes place, and the result will be an int. Only the five low-order bits of the right-hand side will be used. This prevents you from shifting more than the number of bits in an int. If you’re operating on a long, you’ll get a long result. Only the six low-order bits of the right-hand side will be used, so you can’t shift more than the number of bits in a long.

For example:

int i = -1;
i >>>= 123; // For int, only low-order 5 bits of 123 will be used: 27
// So it is actually i >>>= 27
// Result is 31
System.out.println(i);


Refer to Page 43 for primitive type in Java

No comments:

Post a Comment