Convert int to unsigned byte in Java

Casting to byte throws away all but the lowest 8 bits.

int i = 150;        // 00000000 00000000 00000000 10010110
byte b = (byte) i;  //                            10010110

System.out.println(b);                      // -106
System.out.println(Byte.toUnsignedInt(b));  //  150

Comments

Be the first to comment!