How to write Java code that uses iushr, Logical shift right int

iushr in Java byte code logically shift right an integer. But code like a >> 2 is compiled to use ishr.

Is there a way to write Java code that compiles to Java byte code that contains iushr?

Yes, you can write Java code that compiles to bytecode using iushr.

The key is:

Use the >>> operator instead of >>.

Here’s the difference:

  • >> is arithmetic right shift (signed), and compiles to the ishr bytecode instruction.
  • >>> is logical right shift (unsigned), and compiles to the iushr bytecode instruction.

Example:

int a = -8;
int b = a >>> 2;

This will compile to bytecode that includes the iushr instruction.

In contrast:

int a = -8;
int b = a >> 2;

This will compile to ishr.

Summary:

To get iushr in bytecode, use the >>> operator in your Java source. That’s the only way in standard Java to compile down to that specific instruction.