views:

327

answers:

3

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?

+12  A: 

You can use Arrays.copyOfRange() for that.

tangens
Whoa. Didn't know about that.
Jonathan Feinberg
@Jonathan Feinberg: It's new in Java 6.
R. Bemrose
Thank you very much. This works without any error !!!
Tara Singh
+3  A: 

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;
}
Bozho
-1 this is not the same as the standard version. It is not type-safe (you can pass it an `Integer[]` and assign the result to a `String[]` variable.) `Arrays.copyOfRange(T[], int, int)` returns `T[]`. You may be mixing it up with the other version that takes a `Class` argument.
finnw
@finnw: the other method is just overloaded. I merged them but forgot to remove the 2nd type parameter. Now it's fixed.
Bozho
A: 

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

Ron