views:

120

answers:

3

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?

+5  A: 

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.

Pavel Minaev
does that mean 0-127 are the same for both (a java 0 == the other 0) but everything after 128 in the other corresponds to a negative java byte?
hatorade
Yes, exactly. I've edited the question to detail the transformation. See http://en.wikipedia.org/wiki/Two's_complement for more info.
Pavel Minaev
+2  A: 

Java's integral types (including byte) are signed: they range from -128 to 127, rather than 0 to 255 like you might expect. Any number with a high bit of 1 (1### ####) will be negative.

Lots of people have written about this.

Samir Talwar
+1  A: 
erickson