ByteBuffer

Convert between ByteBuffer and byte array

With this example we are going to demonstrate how to convert between ByteBuffers and byte arrays. In short, to make a conversion between a ByteBuffer and a byte array you should:

  • Create a byte array and wrap it into a ByteBuffer. The buffer’s capacity and limit will be the array’s length and its position will be zero.
  • Retrieve the bytes between the current position and the limit of the buffer. The new byte array’s length is set to the number of remaining elements in the buffer, using the remaining() API method and then the bytes are transfered from the buffer to the byte array, using the get(byte[] dst, int offset, int length) API method.
  • Retrieve all bytes in the buffer. First the buffer position is set to 0 and the buffer limit is set to its capacity, with the clear() API method, then the new byte array’s length is set to the buffer’s capacity and then again the get(byte[] dst, int offset, int length) API method transfers bytes from the buffer into the array.

 
Let’s take a look at the code snippet that follows.

// Create a byte array
byte[] bytes = new byte[10];

// Wrap a byte array into a buffer
ByteBuffer buf = ByteBuffer.wrap(bytes);

// Retrieve bytes between the position and limit
// (see Putting Bytes into a ByteBuffer)
bytes = new byte[buf.remaining()];

// transfer bytes from this buffer into the given destination array
buf.get(bytes, 0, bytes.length);

// Retrieve all bytes in the buffer
buf.clear();
bytes = new byte[buf.capacity()];

// transfer bytes from this buffer into the given destination array
buf.get(bytes, 0, bytes.length);

 
This was an example of how to convert between a ByteBuffer and a byte array in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button