convert a LongBuffer/IntBuffer/ShortBuffer to ByteBuffer

logoff picture logoff · Jul 26, 2012 · Viewed 15.4k times · Source

I know a quick way to convert a byte/short/int/long array to ByteBuffer, and then obtain a byte array. For instance, to convert a byte array to short array I can do:

byte[] bArray = { 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0 };

ByteBuffer bb = ByteBuffer.wrap(byteArray);
ShortBuffer sb = bb.asShortBuffer();
short[] shortArray = new short[byteArray.length / 2];
sb.get(shortArray);

produces a short array like this: [256, 0, 0, 0, 256, 0, 0, 0].

How can I do the inverse operation using java.nio classes?

Now I am doing this:

shortArray[] = {256, 0, 0, 0, 256, 0, 0, 0};
ByteBuffer bb = ByteBuffer.allocate(shortArray.length * 2);
for (short s : shortArray) {
    bb.putShort(s);
}
return bb.array();

And I obtain the original [1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0] byte array. But I want to use a method like ShortBuffer.asByteBuffer(), not a manual loop to do it.

I have found a request to Sun of 2001, but they did not accept it ;-((

Answer

A.H. picture A.H. · Jul 26, 2012

What about this? :

    bb.asShortBuffer().put(shortArray);

Then bb contains your data.

Full code:

public class Test {
    public static void main(final String args[]) {
        short[] arr = { 256, 0, 0, 0, 256, 0, 0, 0 };
        for (byte b : F(arr)) {
            System.out.print(b);
        }
    }

    public static byte[] F(short[] arr) {
        java.nio.ByteBuffer bb = java.nio.ByteBuffer.allocate(arr.length * 2);
        bb.asShortBuffer().put(arr);
        return bb.array(); // this returns the "raw" array, it's shared and not copied!
    }
}