|
How to put bytes into a ByteBuffer |
|
|
This Java tip demonstrates a method of putting bytes into a ByteBuffer. A ByteBuffer
has a capacity which determines how many bytes it contains.The bytes in a ByteBuffer
can also be set using the relative version of put(), which uses the position and
limit properties of the buffer. In particular, this version of put() sets the byte
at the position and advances the position by one. put() cannot set bytes past the
limit (even though limit might be less than the capacity). The position is
always <= limit and limit is always <= capacity.
// Create an empty ByteBuffer with a 10 byte capacity
ByteBuffer bbuf = ByteBuffer.allocate(10);
// Retrieve the capacity of the ByteBuffer
int capacity = bbuf.capacity(); // 10
// Use the absolute put().
// This method does not affect the position.
bbuf.put((byte)0xFF); // position=0
// Set the position
bbuf.position(5);
// Use the relative put()
bbuf.put((byte)0xFF);
// Get the new position
int pos = bbuf.position(); // 6
// Get remaining byte count
int rem = bbuf.remaining(); // 4
// Set the limit
bbuf.limit(7); // remaining=1
// This convenience method sets the position to 0
bbuf.rewind(); // remaining=7
|
Related Tips
|
Page 1 of 0 ( 0 comments )
You can share your information about this topic using the form below!
Please do not post your questions with this form! Thanks.