Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of the unsigned right shift operator ">>>" in Java?

I understand what the unsigned right shift operator ">>>" in Java does, but why do we need it, and why do we not need a corresponding unsigned left shift operator?

like image 415
Tyler Durden Avatar asked May 26 '13 21:05

Tyler Durden


People also ask

What do you mean by >>> operator in Java?

The >> operator is a signed right shift operator and >>> is an unsigned right shift operator. The left operands value is moved right by the number of bits specified by the right operand.

What is the difference between >> and >>> in Java?

>> is arithmetic shift right, >>> is logical shift right. In an arithmetic shift, the sign bit is extended to preserve the signedness of the number. For example: -2 represented in 8 bits would be 11111110 (because the most significant bit has negative weight).

What is the difference between right shift and unsigned right shift in Java?

That's all about difference between right shift and unsigned right shift operators in Java. Right shift ">>" keeps the sign extension while shifting bit patterns, but right shift without sign doesn't keep the original sign bit intact, it fills with zero.

What is right shift operator used for?

The right-shift operator causes the bit pattern in shift-expression to be shifted to the right by the number of positions specified by additive-expression . For unsigned numbers, the bit positions that have been vacated by the shift operation are zero-filled.


1 Answers

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 ints, 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 ints:

 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.

like image 115
Sergey Kalinichenko Avatar answered Sep 24 '22 05:09

Sergey Kalinichenko