-1

I want to know if it's possible to update a byte buffer.

Say I have the below:

ByteBuffer buffer = ByteBuffer.allocate(56);
buffer.putInt(12);
buffer.putLong(34);    
buffer.put(byte('A'));    

Assuming I want to modify the buffer to say the that first int I put in should be 50, how do I do that.

I want something like:

public void updateByteBuffer(ByteBuffer, int position, int newValue){
  // logic to change buffer.putInt(12); to buffer.putInt(50);
  // So after this function, my ByteBuffer should contain(hex) 50,34 and 'A';
}
Kaleb Blue
  • 487
  • 1
  • 5
  • 20
  • Also, no need to write a custom method for that; [`ByteBuffer` already has it builtin](http://docs.oracle.com/javase/8/docs/api/java/nio/ByteBuffer.html#putInt-int-int-). Note though that the index is in _bytes_. – fge Feb 16 '16 at 19:20
  • @fge buffer.put(byte('A')); is legal in Java..you can check!! – Kaleb Blue Feb 16 '16 at 19:31

1 Answers1

2

You could always just write buffer.putInt(0, 50). That's the overload that accepts an index, as a byte offset, to indicate where to put the argument.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413