Convert unsigned short to int in Java

Use Short.toUnsignedInt to avoid sign extension.

short s = (short) (Short.MAX_VALUE + 7233);  // -25536 or 40000

int signed = s;                         // -25536 (with sign extension)
int unsigned = Short.toUnsignedInt(s);  //  40000 (without sign extension)

Or, equivalently:

int unsigned = s & 0xffff;

Comments

Be the first to comment!