Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy several byte arrays to one big byte array

Tags:

java

arrays

I have one big byte[] array and lot of small byte arrays ( length of big array is sum of lengths small arrays). Is there maybe some quick method to copy one array to another from starting position to ending, not to use for loop for every byte manually ?

like image 812
Damir Avatar asked Jan 28 '11 11:01

Damir


People also ask

How do I combine byte arrays?

To concatenate multiple byte arrays, you can use the Bytes. concat() method, which can take any number of arrays.

How do you copy byte array?

copyOf(byte[] original, int newLength) method copies the specified array, truncating or padding with zeros (if necessary) so the copy has the specified length. For all indices that are valid in both the original array and the copy, the two arrays will contain identical values.

How do you concatenate bytes?

The concat() method of Bytes Class in the Guava library is used to concatenate the values of many arrays into a single array. These byte arrays to be concatenated are specified as parameters to this method. returns the array {1, 2, 3, 4, 5, 6, 7}.

How do you merge bytes in Java?

byte[] one = getBytesForOne(); byte[] two = getBytesForTwo(); byte[] combined = new byte[one. length + two. length]; System. arraycopy(one,0,combined,0 ,one.


2 Answers

You can use a ByteBuffer.

ByteBuffer target = ByteBuffer.wrap(bigByteArray); target.put(small1); target.put(small2); ...; 
like image 197
josefx Avatar answered Sep 28 '22 16:09

josefx


Use System.arraycopy().

You could also apply the solution from a previous answer of mine. Note that for primitive types such as byte you'll have to produce separate versions (one for each primitive type), as generics don't work there.

like image 39
Joachim Sauer Avatar answered Sep 28 '22 17:09

Joachim Sauer