34

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?

1
  • The offset is at the destination array, not the source one. Commented Nov 16, 2012 at 14:34

3 Answers 3

71

You can use Arrays.copyOfRange() for that.

Sign up to request clarification or add additional context in comments.

3 Comments

Whoa. Didn't know about that.
@Jonathan Feinberg: It's new in Java 6.
@Tara note that the end range should not be same as start range. ie if you are extracting from 0,127 then it should be Arrays.copyOfRange(record,0,128);
15

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

2 Comments

-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: the other method is just overloaded. I merged them but forgot to remove the 2nd type parameter. Now it's fixed.
4

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

1 Comment

ByteBuffer skip4Bytes = ByteBuffer.wrap(bytes, 4, bytes.length - 4);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.