6

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?

1
  • 1
    You will get a java.nio.BufferUnderflowException because you need 4 bytes to have an int, but you are only giving the ByteBuffer 2 bytes. Commented Jul 3, 2013 at 18:54

1 Answer 1

7

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

Sign up to request clarification or add additional context in comments.

2 Comments

So you are saying it should be: ByteBuffer bb = ByteBuffer.wrap(new byte[] {0, 0, oldByte[2], oldByte[3]});?
@This0nePr0grammer Yes, according to the docs the default byte order is big endian, so that looks right.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.