Splitting a Byte array

Viewed 62250

Is it possible to get specific bytes from a byte array in java?

I have a byte array:

byte[] abc = new byte[512]; 

and i want to have 3 different byte arrays from this array.

  1. byte 0-127
  2. byte 128-255
  3. byte256-511.

I tried abc.read(byte[], offset,length) but it works only if I give offset as 0, for any other value it throws an IndexOutOfbounds exception.

What am I doing wrong?

3 Answers

Arrays.copyOfRange() is introduced in Java 1.6. If you have an older version it is internally using System.arraycopy(...). Here's how it is implemented:

public static <U> U[] copyOfRange(U[] original, int from, int to) {
    Class<? extends U[]> newType = (Class<? extends U[]>) original.getClass();
    int newLength = to - from;
    if (newLength < 0) {
        throw new IllegalArgumentException(from + " > " + to);
    }
    U[] copy = ((Object) newType == (Object)Object[].class)
        ? (U[]) new Object[newLength]
        : (U[]) Array.newInstance(newType.getComponentType(), newLength);
    System.arraycopy(original, from, copy, 0,
                     Math.min(original.length - from, newLength));
    return copy;
}

You could use byte buffers as views on top of the original array as well.

Related