1

I've got a ByteBuffer that contains 1024 bytes.

I need to overwrite a short within the buffer at a certain offset at key times.

I know the ByteBuffer class has putShort(), but this doesn't overwrite the data, it simply adds it in, which is causing buffer overflows.

I'm guessing that there isn't a direct way of doing this using the ByteBuffer, can someone possibly suggest a way to do this?

Thanks

Thanks to everyone that replied, seemed it could be done I was just using the wrong version of putShort(). I guess that's what happens when you stare at the same piece of code for six hours.

Thanks again

2
  • 5
    ByteBuffer has two putShort methods: putShort(short value) and putShort(int index, short value). Are you sure you are using the right one? Commented Feb 14, 2013 at 16:51
  • I was totally using the wrong one! Thanks Mark, problem solved :) Commented Feb 14, 2013 at 17:01

4 Answers 4

4

Cannot reproduce the problem, all seems OK

    ByteBuffer bb = ByteBuffer.allocate(20);
    bb.putShort(10, (short)0xffff);
    System.out.println(Arrays.toString(bb.array()));

prints

[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, -1, 0, 0, 0, 0, 0, 0, 0, 0]
Sign up to request clarification or add additional context in comments.

Comments

1
int p = b.position();
b.position( ZePlace );
p.putShort( ZeValue );
b.position( p );

http://docs.oracle.com/javase/7/docs/api/java/nio/Buffer.html#position%28%29

Comments

1

For your special case, you can modify directly the backing array using the array() method.

Then just insert your two bytes at the proper indexes:

if(myBuffer.hasArray()) {
    byte[] array = myBuffer.array();
    array[index] = (byte) (myShort & 0xff);
    array[index + 1] = (byte) ((myShort >> 8) & 0xff);
}

Comments

0

I think you can call this version of putShort() that accepts a possition index.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.