jgr208
jgr208

Reputation: 3066

Mixed Integer and String bytebyffer in java

I have a bytebuffer in java that is a mix of string and integer types, here is the code to get a better idea of what I mean.

    int ID_SIZE = 8;
    int LENGTH_SIZE = 8;
    int MESSAGE_SIZE = 30;
    char[] id = new char[ID_SIZE];
    int length = 12;
    String message = "\0";
    for(int i = 0;i<MESSAGE_SIZE;i++)
        message+="a";
    ByteBuffer bbuf = ByteBuffer.allocate(35);
    bbuf.putInt(length);
    bbuf.put(message.getBytes());
    for(int i = 0;i<36;i++)
        System.out.println(bbuf.get(i));

and as the result I get

0
0
0
12
0
97
97
97
97
97
97
97
97
97
97
97
97
97
97
97
97
97
97
97
97
97
97
97
97
97
97
97
97
97
97

I know the 97 is ASCII a. However I am curious as to why before the 12 it is 0 0 0? Does this have anything to do with it being a mixed bytebuffer or is this just normal byetbuffer behavior?

Upvotes: 0

Views: 88

Answers (2)

chiastic-security
chiastic-security

Reputation: 20520

You're storing a 32-bit integer. Each byte that you see when you print out your byte buffer is 8 bits long; so it takes four of them to represent a 32-bit value.

Note that the two implementations of ByteBuffer that come with the JDK use big endian by default, so you're getting 00 00 00 12 rather than 12 00 00 00. You can change this with

bbuf.order(ByteOrder.LITTLE_ENDIAN);

if you want, but if you're just storing and retrieving, then it doesn't really matter as long as you retrieve with the same ordering that you store.

For more information on how an int gets converted to bytes, you might find this article rather helpful.

Upvotes: 1

Louis Wasserman
Louis Wasserman

Reputation: 198461

ByteBuffer.putInt always puts the int as the full 32 bits -- 4 bytes. You're seeing the leading three zero bytes in the length field.

Upvotes: 1

Related Questions