How to split a byte[]
around a byte sequence in Java? Something like the byte[]
version of String#split(regex)
.
Let's take this byte array:[11 11 FF FF 22 22 22 FF FF 33 33 33 33]
and let's choose the delimiter to be[FF FF]
Then the split will result in these three parts:[11 11]
[22 22 22]
[33 33 33 33]
Please note that you cannot convert the byte[]
to String
, then split it, then back because of encoding issues. When you do such conversion on byte arrays, the resulting byte[]
will be different. Please refer to this:
Conversion of byte[] into a String and then back to a byte[]
Solution: To split a byte string into a list of lines—each line being a byte string itself—use the Bytes. split(delimiter) method and use the Bytes newline character b'\n' as a delimiter.
To concatenate multiple byte arrays, you can use the Bytes. concat() method, which can take any number of arrays.
A byte in Java is 8 bits. It is a primitive data type, meaning it comes packaged with Java. Bytes can hold values from -128 to 127. No special tasks are needed to use it; simply declare a byte variable and you are off to the races.
Yes, by definition the size of a variable of type byte is one byte. So the length of your array is indeed array.
I modified 'L. Blanc' answer to handle delimiters at the very beginning and at the very end. Plus I renamed it to 'split'.
private List<byte[]> split(byte[] array, byte[] delimiter)
{
List<byte[]> byteArrays = new LinkedList<byte[]>();
if (delimiter.length == 0)
{
return byteArrays;
}
int begin = 0;
outer: for (int i = 0; i < array.length - delimiter.length + 1; i++)
{
for (int j = 0; j < delimiter.length; j++)
{
if (array[i + j] != delimiter[j])
{
continue outer;
}
}
// If delimiter is at the beginning then there will not be any data.
if (begin != i)
byteArrays.add(Arrays.copyOfRange(array, begin, i));
begin = i + delimiter.length;
}
// delimiter at the very end with no data following?
if (begin != array.length)
byteArrays.add(Arrays.copyOfRange(array, begin, array.length));
return byteArrays;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With