Get bytes from ByteBuffer

Here I will show how to get bytes from a ByteBuffer. This isn’t as simple as it sounds. If you take the bytes with the method array() you will receive a byte array. But this isn’t what you want. (In most cases). With the array() method you will receive the internal byte array so you should have a look to the get() method. If you let fill your destination array with this method it should be what you expect.
I will show it on a sample with Charset.encode, this because older versions of Java ( <1.6 ) do not have a getBytes(Charset) method. (Yes I know, Java 5 is very old but there are some companies that can’t or won’t change the java version faster.)

The sample will use a utf-8 charset and encode some bytes, the result should be placed in a byte array.

Charset utf8Charset = Charset.forName("utf-8");
// Two special chars
char[] characters = { 0x222, 0x123 };
// Lets get a ByteBuffer
ByteBuffer encoded = utf8Charset.encode(new String(characters));
// create new byte[] with the nr of bytes
byte[] resultBuffer = new byte[encoded.remaining()];
// get the bytes
encoded.get(resultBuffer);

doSomeOtherStuff(resultBuffer);

This should give the same as

final char[] characters = { 0x222, 0x123 };
new String(characters).getBytes("utf-8");

If you compare the internal array with the one you receive with the both samples it looks like this:

internal | bytes
  -56    |  -56
  -94    |  -94
  -60    |  -60
  -93    |  -93
    0    |

About the author

Adrian Elsener

Add comment

By Adrian Elsener

Recent Posts