How to use Wrap Method of ByteBuffer in Java

This 0ne Pr0grammer picture This 0ne Pr0grammer · Jul 3, 2013 · Viewed 21.5k times · Source

Okay, so I was looking up what the best way to convert from a byte array to it's numeric value in java was and I came across this link. And the second answer mentions the use of the ByteBuffer class. For those that do not wish to click on the link, originally the question asks if I have:

byte[] by = new byte[8];

How does one convert that to int? Well the answer goes...

ByteBuffer bb = ByteBuffer.wrap(new byte[] {0, 0, 0, 0, 0, 0, 0, 4});
long l = bb.getLong();

System.out.println(l);

Result

4

And that is awesome to learn, but I just want to confirm something before going that route.

Say I have a previously read in byte array that is 8 bytes long.

byte[] oldByte = new byte[8];

then I do...

ByteBuffer bb = ByteBuffer.wrap(new byte[] {oldByte[2], oldByte[3]});
int intValue = bb.getInt();

Will that work/be read in the same manner as the previous example?

Answer

andersschuller picture andersschuller · Jul 3, 2013

The documentation for the ByteBuffer class specifies that the getInt() method reads the next four bytes, so if you are only passing two bytes to the call to wrap, you will get a BufferUnderflowException:

Throws: BufferUnderflowException - If there are fewer than four bytes remaining in this buffer