Reputation: 3638
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
Upvotes: 1
Views: 3948
Reputation: 53829
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);
}
Upvotes: 1
Reputation: 136012
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]
Upvotes: 3
Reputation: 8154
I think you can call this version of putShort() that accepts a possition index.
Upvotes: 0
Reputation: 14853
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
Upvotes: 1