ByteBuffer to int array (each byte)

Tags: ,



Related to question byte array to Int Array, however I would like to convert each byte to an int, not each 4-bytes.

Is there a better/cleaner way than this:

protected static int[] bufferToIntArray(ByteBuffer buffer) {
    byte[] byteArray = new byte[buffer.capacity()];
    buffer.get(byteArray);

    int[] intArray = new int[byteArray.length];

    for (int i = 0; i < byteArray.length; i++) {
        intArray[i] = byteArray[i];
    }

    return intArray;
}

Answer

I’d probably prefer

int[] array = new int[buffer.capacity()];
for (int i = 0; i < array.length; i++) {
  array[i] = buffer.get(i);
}
return array;


Source: stackoverflow