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

Mitch picture Mitch · Mar 20, 2011 · Viewed 114.4k times · Source

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.

Answer

krock picture krock · Mar 20, 2011

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