Convert unsigned byte to short in Java

Use Byte.toUnsignedInt to avoid sign extension, then cast to short.

byte b = (byte) 0b10010110;                     // -106 or 150

short signed = b;                               // -106 (with sign extension)
short unsigned = (short) Byte.toUnsignedInt(b); //  150 (without sign extension)

Or, equivalently:

short unsigned = (short) (b & 0xff);

Comments

Be the first to comment!