Java ByteBuffer Class

I am reading byte [] from a device and trying to interpret it as an integer array in Java using the ByteBuffer class, but I have an out of bounds index error. See 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??



source to share

1 answer

The class ByteBuffer

internally stores several properties of the buffer. The most important is the position (of the virtual "cursor") in the buffer. This position can be read with byteBuffer.position()

and written down with byteBuffer.position(123);


The JavaDoc ByteBuffer.asIntBuffer

now says:

The contents of the new buffer will start at the current buffer position.

This means that, for example, when you have ByteBuffer

with a capacity of 16 elements and position()

this ByteBuffer

is 4, then the resulting IntBuffer

will only represent the remaining 12 elements.

After the call, the byteBuffer.put(bytes)

byte buffer position is advanced (depending on the length of the byte array). Thus IntBuffer

, the one you create has less capacity.

To solve this problem, you can call byteBuffer.rewind()

or byteBuffer.position(0)

after the call byteBuffer.put(bytes)

. (Which one is more appropriate depends on the intended use pattern)



All Articles