0

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?

4
  • You might find the documentation for ByteBuffer.putInt helpful. Commented Nov 17, 2014 at 20:17
  • @VGR actually had just figured that out. But now am curious, why when I put a number such as 150 does it display 0 0 0 -56 instead of using all 4 to sum to 150? Commented Nov 17, 2014 at 20:18
  • Because that's what you get when you treat 150 as a signed byte. If n >= 128, then n as a signed byte is n - 256. Commented Nov 17, 2014 at 20:19
  • @jgr208 if it just used four values to sum to the int value, you wouldn't be able to store values of more than 1024. Commented Nov 17, 2014 at 20:27

2 Answers 2

1

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.

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

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.