What is the easy way to concatenate two byte
arrays?
Say,
byte a[];
byte b[];
How do I concatenate two byte
You can use third party libraries for Clean Code like Apache Commons Lang and use it like:
byte[] bytes = ArrayUtils.addAll(a, b);
Here's a nice solution using Guava's com.google.common.primitives.Bytes
:
byte[] c = Bytes.concat(a, b);
The great thing about this method is that it has a varargs signature:
public static byte[] concat(byte[]... arrays)
which means that you can concatenate an arbitrary number of arrays in a single method call.
byte[] result = new byte[a.length + b.length];
// copy a to result
System.arraycopy(a, 0, result, 0, a.length);
// copy b to result
System.arraycopy(b, 0, result, a.length, b.length);
Most straightforward:
byte[] c = new byte[a.length + b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
The most elegant way to do this is with a ByteArrayOutputStream
.
byte a[];
byte b[];
ByteArrayOutputStream outputStream = new ByteArrayOutputStream( );
outputStream.write( a );
outputStream.write( b );
byte c[] = outputStream.toByteArray( );
If you prefer ByteBuffer
like @kalefranz, there is always the posibility to concatenate two byte[]
(or even more) in one line, like this:
byte[] c = ByteBuffer.allocate(a.length+b.length).put(a).put(b).array();