1

Possible Duplicate:
byte array to Int Array

I have a large array of bytes, can I somehow interpret it as an array of ints, such that each entry is just four of the original bytes?

I mean something like this:

for (int i = 0; i < byteArray.length; i += 4) {
    intArray[i / 4] = byteArray[i] << 24 + byteArray[i+1] << 16 + byteArray[i+2] << 8 + byteArray[i+3];
}

but rather than copying the whole array byte by byte which takes forever because the array is huge, just read ints off the array that already exists.

Community
  • 1
  • 1

3 Answers3

4

Using this code:

IntBuffer intarray = ByteBuffer.wrap(bytearray).order(ByteOrder.BIG_ENDIAN).asIntBuffer();
 intarray.get(100);

will take very few extra heap space. Actually, it wraps byte array and creates a int array view. Significantly faster, in my PC for buffer size of INT_MAX takes few nanoseconds.

Arpssss
  • 3,850
  • 6
  • 36
  • 80
1

Q: Is it possible to change the type of an array in Java?

A: In general, "no". You'd have to copy/convert item by item.

In this specific case: yes, certainly. Just use asIntBuffer(). For example:

import java.nio.*;
import java.nio.IntBuffer;
import java.nio.ByteBuffer;

public class MyClass {

  public static void main(String[] args) throws Exception {
    ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
    int[] array = new int[] { 1, 2, 3, 4 };
    IntBuffer IntBuf = byteBuffer.asIntBuffer();
    IntBuf.put(array);
    ...

Note that these conversions (and related "flip", "wrap", ability to change byte order, etc) were introduced with java.nio.

paulsm4
  • 114,292
  • 17
  • 138
  • 190
  • PS: Bohemian is correct. The *original* array is unchanged. asIntBuffer() and friends just *copies* the array. Transforming as needed. Very, very efficiently. – paulsm4 Aug 10 '12 at 01:29
1

No. The type of an array is invariant.

No if's, but's or maybe's.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • You're absolutely correct :) I think the OP just wanted to know if there was an alternative to copying and converting the array element-by-element. And, in this case, there is. – paulsm4 Aug 10 '12 at 01:30