Splitting a Byte array
60,473
Solution 1
You can use Arrays.copyOfRange()
for that.
Solution 2
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;
}
Solution 3
You could use byte buffers as views on top of the original array as well.
Comments
-
Tara Singh almost 3 years
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.
- byte 0-127
- byte 128-255
- 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 anIndexOutOfbounds
exception.What am I doing wrong?