How to use Wrap Method of ByteBuffer in Java
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
Related videos on Youtube
This 0ne Pr0grammer
Updated on July 04, 2020Comments
-
This 0ne Pr0grammer almost 4 years
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?
-
Brinnis almost 11 yearsYou will get a java.nio.BufferUnderflowException because you need 4 bytes to have an int, but you are only giving the ByteBuffer 2 bytes.
-
-
This 0ne Pr0grammer almost 11 yearsSo you are saying it should be:
ByteBuffer bb = ByteBuffer.wrap(new byte[] {0, 0, oldByte[2], oldByte[3]});
? -
andersschuller almost 11 years@This0nePr0grammer Yes, according to the docs the default byte order is big endian, so that looks right.