0

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;
}
Community
  • 1
  • 1
mikhail
  • 5,019
  • 2
  • 34
  • 47

3 Answers3

3

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;
Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
0

for kotlin programmers..

fun getIntArray(byteBuffer: ByteBuffer): IntArray{
    val array = IntArray(byteBuffer.capacity())
    for (i in array.indices) {
        array[i] = byteBuffer.getInt(i)
    }
    return array
}
Sjd
  • 1,261
  • 1
  • 12
  • 11
0

This produces an int array:

int[] intArray = byteBuffer.asInBuffer().array()

Johann
  • 27,536
  • 39
  • 165
  • 279
  • 1
    It won't work for JDK though, it will throw `UnsupportedOperationException`. `asIntBuffer()` creates a **view**, but `array()` requires something that is backed by an accessible array to work. However, this method works on Android. – itachi Jul 19 '21 at 17:15