Tag Archives: Java – Convert bytes to unsigned bytes

Java – Convert bytes to unsigned bytes

https://mkyong.com/java/java-convert-bytes-to-unsigned-bytes/

In Java, byte is an 8-bit signed (+,-) data type, it has value of Byte.MIN_VALUE -128 to Byte.MAX_VALUE 127 (inclusive).

Java doesn’t have unsigned bytes (0 to 255). To make unsigned bytes, we can cast or widen a byte into an int and mask with 0xff to avoid sign extension.

Further Reading

Sign extension

Two’s complement

1. unsigned bytes

Java 8 A new Byte.toUnsignedInt() is introduced to convert the signed bytes into unsigned bytes.

JavaExample1.java


package com.mkyong;

public class JavaExample1 {

    public static void main(String[] args) {

        byte input = (byte) -2; // -2 (signed) and 254 (unsigned)

        System.out.println(input);                              // -2
        System.out.println(convertBytesToUnsignedBytes(input)); // 254

        // Java 8
        System.out.println(Byte.toUnsignedInt(input));          // 254

    }

    public static int convertBytesToUnsignedBytes(Byte x) {

        // auto cast to int
        return x & 0xFF;

        // explicit cast
        // return ((int) x) & 0xFF;

    }
}

Output


-2
254
254

2. Explanation

Read comments for self-explanatory.

JavaExample2.java


package com.mkyong;

public class JavaExample2 {

    public static void main(String[] args) {

        byte input = (byte) -2;                         // -2 (signed) and 254 (unsigned)

        // -2 = 1111 1110 , two's complement
        System.out.println("Input : " + input);

        // byte (8 bits) cast/widen to int (4 bytes, 16 bits), sign extension will apply
        // 1111 1111 | 1111 1111 | 1111 1111 | 1111 1110
        int input2 = (int) input;

        System.out.println("Input [Binary] : " + Integer.toBinaryString(input2));

        // 1111 1111 | 1111 1111 | 1111 1111 | 1111 1110
        // &
        // 0000 0000 | 0000 0000 | 0000 0000 | 1111 1111 (0xFF) , get last 8 bits
        // =============================================
        // 0000 0000 | 0000 0000 | 0000 0000 | 1111 1110  unsigned bytes
        int result = input2 & 0xff;

        System.out.println(result); // 254
        System.out.println(Integer.toBinaryString(result)); // 1111 1110

        // Java 8
        System.out.println(Byte.toUnsignedInt(input));

    }

}

Output


Input : -2
Input [Binary] : 11111111111111111111111111111110
254
11111110
254

P.S Correct me if the above binary explanation is incorrect

References

Java Data Type

Java and “& 0xFF” example

Sign extension

Two’s complement

0xff
binary
bytes
java 8
sign extension
two complement