Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending a byte[] to the end of another byte[] [duplicate]

I have two byte[] arrays which are of unknown length and I simply want to append one to the end of the other, i.e.:

byte[] ciphertext = blah; byte[] mac = blah; byte[] out = ciphertext + mac; 

I have tried using arraycopy() but can't seem to get it to work.

like image 495
Mitch Avatar asked Mar 20 '11 13:03

Mitch


People also ask

How do you add byte arrays together?

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

What does byte [] do in Java?

The Java byte keyword is a primitive data type. It is used to declare variables. It can also be used with methods to return byte value. It can hold an 8-bit signed two's complement integer.

Can you print [] byte?

You can simply iterate the byte array and print the byte using System. out. println() method.


2 Answers

Using System.arraycopy(), something like the following should work:

// create a destination array that is the size of the two arrays byte[] destination = new byte[ciphertext.length + mac.length];  // copy ciphertext into start of destination (from pos 0, copy ciphertext.length bytes) System.arraycopy(ciphertext, 0, destination, 0, ciphertext.length);  // copy mac into end of destination (from pos ciphertext.length, copy mac.length bytes) System.arraycopy(mac, 0, destination, ciphertext.length, mac.length); 
like image 117
krock Avatar answered Sep 20 '22 06:09

krock


Perhaps the easiest way:

ByteArrayOutputStream output = new ByteArrayOutputStream();  output.write(ciphertext); output.write(mac);  byte[] out = output.toByteArray(); 
like image 27
Vadim Avatar answered Sep 22 '22 06:09

Vadim