Convert unsigned short to long in Java

Use Short.toUnsignedLong to avoid sign extension.

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

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

Or, equivalently:

int unsigned = s & 0xffff;

Comments

Be the first to comment!