V6069. Unsigned right shift assignment of negative 'byte' / 'short' value.


The analyzer has detected an unsigned right shift assignment operation (>>>=) applied to a potentially negative value of type 'byte' or 'short'. Such a shift may lead to unpredictable results.

When right-shifting a value, you often want to avoid promotion of the sign bit and have the vacant bits on the left padded with 0's, no matter the sign of the most significant bit. This is what the unsigned bitwise right shift operator, >>>, is used for.

The shift can also be combined with the assignment operator (>>>=), but the program's behavior may be non-obvious when using such a compound operator with the type 'byte' or 'short'. This has to do with the fact that values of these types will be first implicitly cast to 'int' and right-shifted, and then they will get truncated when casting back to the original type.

If you try compiling the following code sample:

void test(byte byteValue, boolean isFlag)
{
  ....
  if (isFlag)
  {
   byteValue = byteValue >>> 5;  
  }
  ....
}

you will get this error:

error: incompatible types:
       possible lossy conversion from int to byte
       byteValue = byteValue >>> 5;
                             ^

It proves what was said above about type promotion to 'int', and the compiler will not allow casting 'int' to 'byte' unless it is done explicitly. It means that you know what you are doing. If you compile the same snippet after changing it slightly:

....
byteValue >>>= 5;
....

it will compile well. When executing this code, the value will be promoted, shifted, and then demoted back to the original type.

Because of that, such shift assignment operations involve behavior that the developer might not expect. When applying such an operation to a positive number, the code will be working as expected. But what about negative numbers?

The following contrived example demonstrates what happens when using a right shift assignment with the value -1 of type 'byte':

byte byteValue = -1; // 0xFF or 0b1111_1111
byteValue >>>= 4;
assertTrue(byteValue == 0x0F); // byteValue == 0b0000_1111 

Since the value is 8 bits (i.e. one byte) long, the developer expects to have only the 4 least significant bits left as a result of the unsigned right shift by 4 bits. However, to their surprise, 'assertTrue' fails!

This happens because 'byteValue' is implicitly promoted to 'int', shifted, and truncated back to 'byte':

byteValue == 0xFF (byte): 11111111
Promotion to 'int'      : 11111111 11111111 11111111 11111111
Shift by 4              : 00001111 11111111 11111111 11111111
Casting to 'byte'       : 11111111

It may seem as if the unsigned shift (>>>=) does not work properly. But it is actually consistent and logical. It is just that there is this subtle detail, which you have to keep in mind when working with values of type 'byte' or 'short'.


Bugs Found

Checked Projects
346
Collected Errors
13 188