3

I'm reading a byte[] from a device and trying to interpret it as an integer array in Java with the help of the ByteBuffer class but I'm getting an index out of bounds error. Look here:

byteBuffer.put(bytes); // put the array of bytes into the byteBuffer        

System.out.println("the value I want is " + byteBuffer.getInt(16*4)); // gives me the number I want, but I'd rather deal with an integer array like this:

System.out.println("the value I want is " + byteBuffer.asIntBuffer().get(16)); // index out of bounds? Why??
3
  • 1
    Can you post a short but complete program demonstrating the problem? Commented Sep 24, 2014 at 16:55
  • I found out it works if I do a byteBuffer.position(0) before I call byteBuffer.asIntBuffer(). Seems weird to have to do that but it works. Commented Sep 24, 2014 at 16:57
  • 3
    Probably because the position of the ByteBuffer is changed. In the javadoc for asIntBuffer: The content of the new buffer will start at this buffer's current position. Changes to this buffer's content will be visible in the new buffer, and vice versa; the two buffers' position, limit, and mark values will be independent. Commented Sep 24, 2014 at 16:58

1 Answer 1

5

The ByteBuffer class internally stores several properties of the buffer. The most important one being the position (of a virtual "cursor") in the buffer. This position can be read with byteBuffer.position(), and written with byteBuffer.position(123);.

The JavaDoc of ByteBuffer.asIntBuffer now states:

The content of the new buffer will start at this buffer's current position.

This means that, for example, when you have a ByteBuffer with a capacity of 16 elements, and the position() of this ByteBuffer is 4, then the resulting IntBuffer will only represent the remaining 12 elements.

After calling byteBuffer.put(bytes), the position of the byte buffer is advanced (depending on the length of the byte array). The IntBuffer that you are creating then has a smaller capacity, accordingly.

To solve this, you can call byteBuffer.rewind() or byteBuffer.position(0) after you called byteBuffer.put(bytes). (Which one is more appropriate depends on the intended usage pattern)

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.