Home > database >  ByteBuffer put method adds 0 after ByteArray
ByteBuffer put method adds 0 after ByteArray

Time:09-27

I currently ran into a actually quite weird problem with the put method of java.nio.bytebuffer and I wondered if you might know the answer to it, so let's get to it.

My goal is it to concatenate some data to a bytebuffer. The problem is after I call the put method it always adds a 0 after the byte array.

Here is the method which has those side effects:

    public ByteBuffer toByteBuffer() {

    ByteBuffer buffer = ByteBuffer.allocateDirect(1024));
    
    buffer.put(type.name().getBytes()); // 0 added here

    data.forEach((key, value) -> {
        buffer.putChar('|');
        buffer.put(key.getBytes()); // 0 added here
        buffer.putChar('=');
        buffer.put(value.getBytes()); // 0 added here
    });

    buffer.flip();

    return buffer;
}

Expected Output should look something like this:

ClientData|OAT=14.9926405|FQRIGHT=39.689075|..... 

Actual Ouptut where _ represents the 0s:

ClientData_|OAT_=14.9926405_|FQRIGHT_=39.689075_|.....

The documentation doesn't say anything about this side effect. Also the put method only puts a 0 in between the byte arrays but not at the very end of the buffer.

I assume the method might be wrong or at least not properly documented, but I really have no clue why it would behave that way.

CodePudding user response:

I think you may be slightly misinterpreting what is happening here. I note your comment about "but not at the very end of the buffer".

The \0 is actually coming from the putChar(char) calls, not the put(byte[]) calls. As it says in the docs (emphasis added):

Writes two bytes containing the given char value, in the current byte order

The default byte order is big endian; given that the chars you are writing are in the 7-bit ASCII range, this means "the byte you want" is going to be preceded by 0x00.

If you want to write a byte, use put(byte):

buffer.put((byte) '|');
  • Related