Java ByteBuffer with signed and unsigned types converts a byte array to an integer

I was expecting this:

ByteBuffer.wrap(new byte[] { 0, 0, 0, -34 }).getInt() == 222 

However, the following is true:

 ByteBuffer.wrap(new byte[] { 0, 0, 0, -34 }).getInt() == -570425344 

How do I get around this one of many Java limitations with signed / unsigned types or do I need to roll back my own completely?

+4
source share
2 answers

code:

 public static void main(String[] args) { ByteBuffer bb = ByteBuffer.wrap(new byte[] { 0, 0, 0, -34 }); System.out.println(bb.order()); System.out.println(bb.getInt() == 222); bb.rewind(); bb.order(ByteOrder.LITTLE_ENDIAN); System.out.println(bb.order()); System.out.println(bb.getInt() == -570425344); } 

Console:

 BIG_ENDIAN true LITTLE_ENDIAN true 

Addendum: for reference: "The order of the created byte buffer is always BIG_ENDIAN ." - ByteBuffer#order()

+5
source

The result you observe is suitable for a small-end machine. I suspect that if you run the following, you will get a LITTLE_ENDIAN answer.

 ByteBuffer bb = ByteBuffer.wrap(new byte[] { 0, 0, 0, -34 }); System.out.println(bb.order()); 

If you want to force a large size for your buffer, do the following:

 ByteBuffer bb = ByteBuffer.wrap(new byte[] { 0, 0, 0, -34 }); bb.order(ByteOrder.BIG_ENDIAN); System.out.println(bb.order()); System.out.println(bb.getInt( )); 

Must print:

 BIG_ENDIAN 222 
+3
source

All Articles