Convert unsigned byte to long in Java

Use Byte.toUnsignedInt to avoid sign extension.

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

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

Or, equivalently:

long unsigned = b & 0xff;

Comments

Be the first to comment!