The >>>
operator lets you treat int
and long
as 32- and 64-bit unsigned integral types, which are missing from the Java language.
This is useful when you shift something that does not represent a numeric value. For example, you could represent a black and white bit map image using 32-bit int
s, where each int
encodes 32 pixels on the screen. If you need to scroll the image to the right, you would prefer the bits on the left of an int
to become zeros, so that you could easily put the bits from the adjacent int
s:
int shiftBy = 3;
int[] imageRow = ...
int shiftCarry = 0;
// The last shiftBy bits are set to 1, the remaining ones are zero
int mask = (1 << shiftBy)-1;
for (int i = 0 ; i != imageRow.length ; i++) {
// Cut out the shiftBits bits on the right
int nextCarry = imageRow & mask;
// Do the shift, and move in the carry into the freed upper bits
imageRow[i] = (imageRow[i] >>> shiftBy) | (carry << (32-shiftBy));
// Prepare the carry for the next iteration of the loop
carry = nextCarry;
}
The code above does not pay attention to the content of the upper three bits, because >>>
operator makes them
There is no corresponding <<
operator because left-shift operations on signed and unsigned data types are identical.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…