Incompatible types of Java errors between short and int. Not sure why

In the following code, I have the error "a possible loss of accuracy is found: int is required: short". I understand what the error means, but I'm just wondering why I get it. Of course, the function should return a short type (I don’t see how there can be a loss of accuracy, the code should return a 16-bit integer). Can someone explain to me why the following code seems to require an int type?

static short a() { short[] payload = { 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000 }; short offset = 2; return (payload[offset - 2] << 8 & 0xff00) + (payload[offset - 1] & 0xff); } 

Thanks!

+8
java bit-manipulation precision
source share
1 answer

Java arithmetic operations in short always return int , in part to prevent overflow and partially reflect the JVM base bytecode, which does not distinguish between arithmetic operations on int , short or byte . But basically, (payload[offset - 2] << 8 & 0xff00) is an int , and it wants you to drop it to a short one.

+16
source share

All Articles