Search code examples
javabitwise-operators

How to convert 2 bytes from byte[] to a Char / short (2 bytes)?


My goal is to convert 2 bytes to a Char.

The input will be from a byte[] then converted to char. My initial strategy was to use bitwise operations.

My expected result: 0xFF << 8 | 0xFF equals to 0xFFFF. It does. But, in practice it does not because before the bitwise operations, I need to store the data in byte[].

My actual result: Due to the way I access the data. (byte) 0xFF << 8 | (byte) 0xFF will equal to -1.

byte[] bytes = new byte[]{(byte) 0xFF, (byte) 0xFF};

int integer = bytes[0] << 8 | bytes[1]; // -1 or 0xFFFFFFFF

Solution

  • You need:

    int integer = (bytes[0] & 0xff) << 8 | (bytes[1] & 0xff);
    

    Which gives the expected value of 65535.