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;
}

3 Answers 3

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;
Sign up to request clarification or add additional context in comments.

Comments

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
}

Comments

-1

This produces an int array:

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

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.