Wednesday, July 29, 2015

Java converting bytes to integers

Saw this Java method on github for converting Little Endian bytes to an integer:


private static int U8TO32_LE(byte[] x, int i) {
    return x[i] | (x[i + 1] << 8) | (x[i + 2] << 16) | (x[i + 3] << 24);
}

The implementation above is incorrect.  In Java, bytes are signed.  So the signed bit will got extended when a byte is casted as integer.  The correct way to do it should be:

private static int U8TO32_LE(byte[] x, int i) {
    return (x[i] & 0xff) | ((x[i + 1] & 0xff) << 8) | ((x[i + 2] & 0xff) << 16) | ((x[i + 3] & 0xff) << 24);
}





No comments: