Does 0xFFFF need to be shorter?
I’m developing an Android 2.3.3 application using Java.
I have the following code:
Short CRCAux = 0xffff;
I
get a warning in eclipse that I have to convert this value to short:
short
CRCAux = (short) 0xffff;
I’m migrating an iOS app to Android, and in iOS, CRCAux
is UInt16
.
Why does the compiler need to convert this value to short? Is short a signed int 16-bit data type?
Solution
Literals like 0xFFFF are assumed by the Java compiler to be int types. So it’s perfectly correct that you’re getting a warning here, because int values 0x0000FFFF don’t fit short (the compiler doesn’t know that you don’t care about truncating high zeros in this particular case).
In this case, if you write a 16-bit value as a signed value, the compiler will accept it without casting:
short CRCAux = -1;
The short type can be used to store the value of uint16 (16-bit two’s complement is only 16 bits after all, it’s just a matter of interpretation of those bits).
That is, because Java assumes that these 16 bits represent signed two’s complement. Many operators (shift, multiply/division, and larger/smaller comparisons) get very different semantics. Unless you know exactly what you’re doing, there’s a good chance this will break the code you’re porting. Char is better suited for this scenario because it provides the desired “unsigned” behavior.