I am trying to "clean up" a ByteBuffer
to be all zero bytes (all 0x00
). I tried to loop over all positions in the buffer and set them to 0x00
, but the efficiency is bad. Is there any better way to quickly clear a ByteBuffer
- similar to what BitSet.clear()
does?
Please note that ByteBuffer.clear()
is not an appropriate solution for me in this scenario--I have to erase all the data inside of the buffer, and not just reset the pointer to the beginning.
Any hints?
Edit: the ByteBuffer is used as a part of the hash table, and it maintains the references of the hash table entries. Every time when the hash table needs to be flushed, I have to reset the hash table entries for later hash table insertion. Since the hash table is accessed in a random-fashion, I cannot simply clear() the state of the byte buffer.
The clear() method of java. nio. ByteBuffer Class is used to clear this buffer. The position is set to zero, the limit is set to the capacity, and the mark is discarded.
ByteBuffer is useful for binary conversion of data to and from Java primitive data. For instance suppose you want to convert an integer to an array of bytes. The following shows an integer and the hex value of the bytes. To convert the integer to a byte array, you can use the ByteBuffer as folows.
Note that in JDK document's words rewind() and clear() looks alike for "cleaning" the ByteBuffer . Actually the old data exists, furthermore rewind() should be used before channel-write or get operation and clear() corresponds to channel-read or put operation.
ByteBuffer rewind() methods in Java with Examples ByteBuffer Class is used to rewind this buffer. The position is set to zero and the mark is discarded. Invoke this method before a sequence of channel-write or get operations, assuming that the limit has already been set appropriately.
Have you tried using one of the ByteBuffer.put(byte[])
or ByteBuffer.put(ByteBuffer)
methods to write multiple zeros in one go? You could then iterate over the buffer in chunks of 100 or 1000 bytes, or whatever, using an array or buffer pre-filled with zeros.
Downside: this is an optional operation, so not all implementations of ByteBuffer are required to provide it...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With