I’m developing an Android 2.3.3 application with Java.
I have the following code:
short CRCAux = 0xffff;
I get a warning in eclipse that I have to cast this value to short:
short CRCAux = (short) 0xffff;
I’m migrating an iOS application to Android, and in iOS, CRCAux is UInt16.
Why the compiler needs to cast that value to short? Is short a signed int 16bit data type or not?
Literals like 0xFFFF are presumed to be of type int by the java compiler. So its very correct you get the warning here, since the int value 0x0000FFFF does not properly fit into the short (the compiler can not know that you do not care about the truncation of the upper zeros in this special case).
In this case, if you write the 16 bit value as signed value, the compiler will accept it without cast:
The short type can be used to store the value of an uint16 (16 bits twos complement are just 16 bits after all, its just a matter of interpretation of those bits).
That said, since java assumes those 16 bits to represent a signed twos complement number. You get very different semantics with many operators (shift, multiply/divide and greater/smaller comparisons). Unless you know exactly what you’re doing this will most likely break the code you are porting. Char is a better fit in this case since it delivers the desired ‘unsigned’ behavior.