Question

So I'm trying to figure out why when I insert/put into a ByteBuffer the indexes are always 1 greater than they should be. For example:

public static void main(String[] args) throws Exception
    {
        byte[] memory = new byte[10]; // 3MB memory
        ByteBuffer byteBuffer = ByteBuffer.wrap(memory);

        char character = 'G';

        byteBuffer.putChar(0, character); // 71 at index 1
        byteBuffer.putChar(5, character); // 71 at index 6
        byteBuffer.putChar(3, character); // 71 at index 4

        for(Byte myByte : byteBuffer.array())
        {
            System.out.println(myByte.byteValue());
        }
}

How can I get this to insert into the indexes I want?

Was it helpful?

Solution

The documentation for that function states:

Writes two bytes containing the given char value, in the current byte order, into this buffer at the given index.

It sounds like you have a big-endian byte-order, hence the value you expected to see is being written into the second position (probably with a 0-byte in the first position).

You should use the equivalent put method instead, which writes a single byte.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top