Convert unsigned byte to int in Java

Use Byte.toUnsignedInt to avoid sign extension.

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

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

Or, equivalently:

int unsigned = b & 0xff;

Comments

Be the first to comment!