Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differing behaviour when shifting bits in java

Tags:

java

I'm working with bit shifting in Java and have the following piece of code that works as expected:

final byte value = 1;
final int shift = 1;
byte result = value << shift;

This produces the value 2 as expected. If however I attempt to extract this into a method like so:

private void shiftAndCheck(final byte value, final int shift) {
  byte result = value << shift;
}

This results in a compilation error:

java: incompatible types: possible lossy conversion from int to byte

The question is what is it about the method that causes this to fail?

like image 625
imrichardcole Avatar asked Sep 25 '22 13:09

imrichardcole


1 Answers

Since the value and shift are compile-time constants in this snippet:

final byte value = 1;
final int shift = 1;
byte result = value << shift;

then the compiler inlines their values (replaces all the occurrences of value and shift with their actual values of 1) and can verify before Runtime that the result of value << shift won't cause any loss of precision.


Meanwhile, for the second snippet:

private void shiftAndCheck(final byte value, final int shift) {
  byte result = value << shift;
}

the compiler has no evidence that shift will represent such value, which wouldn't cause loss of precision and that's why raises a compilation error.

If compilation was possible in this case, then you'd have been able to do shiftAndCheck(1, 32); which would result in overflowing the byte type.

like image 190
Konstantin Yovkov Avatar answered Oct 12 '22 05:10

Konstantin Yovkov