Java – After reading in bytes from file, most are right except 1 is wrong and negative


In Java, I just read a file into a ByteBuffer. When I started checking to make sure that the ByteBuffer contained the right bytes, I noticed that it had mostly the correct start and end bytes, except for the 3rd byte, it has -117 instead of what emacs says should be 139 (8b in hexl-mode). What gives? Does this have something to do with Big/Little Endian..?

Just to be clear, according to emacs the first four bytes should be:

1f:8b:08:00 which is equal to 31 139 8 0

and my java gets:

31 -117 8 0

Any ideas?

Best Solution

Java byte is signed, and therefore its range is -128..127 rather than 0..255. Taking that into account, your bytes are correct. If the unsigned value of the byte is X, signed one is (X - 256) - thus, for 139, the signed value is 139 - 256 = -117.

Related Question