Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Wrap Method of ByteBuffer in Java

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?

like image 818
This 0ne Pr0grammer Avatar asked Jul 03 '13 18:07

This 0ne Pr0grammer


1 Answers

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

like image 191
andersschuller Avatar answered Sep 29 '22 04:09

andersschuller