In the following code I have an error
"possible loss of precision
found : int
required: short".
I understand what the error means but I'm just wondering why I'm getting it. Surely the function should return a type of short (I can't see how there could be any loss of precision, the code should return a 16 bit integer). Can anyone clear up for me why the following code seems to require the type int?
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!
Answer
Java arithmetic operations on short
always return int
, partly to help prevent overflow, and partly to reflect the underlying JVM bytecode, which doesn't distinguish between arithmetic operations on int
, short
, or byte
. But basically, (payload[offset - 2] << 8 & 0xff00)
is an int
, and it wants you to cast it back down to a short.
No comments:
Post a Comment