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

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.

This question is related to java byte bytearray arrays

The answer is


The other provided solutions are great when you want to add only 2 byte arrays, but if you want to keep appending several byte[] chunks to make a single:

byte[] readBytes ; // Your byte array .... //for eg. readBytes = "TestBytes".getBytes();

ByteArrayBuffer mReadBuffer = new ByteArrayBuffer(0 ) ; // Instead of 0, if you know the count of expected number of bytes, nice to input here

mReadBuffer.append(readBytes, 0, readBytes.length); // this copies all bytes from readBytes byte array into mReadBuffer
// Any new entry of readBytes, you can just append here by repeating the same call.

// Finally, if you want the result into byte[] form:
byte[] result = mReadBuffer.buffer();

You need to declare out as a byte array with a length equal to the lengths of ciphertext and mac added together, and then copy ciphertext over the beginning of out and mac over the end, using arraycopy.

byte[] concatenateByteArrays(byte[] a, byte[] b) {
    byte[] result = new byte[a.length + b.length]; 
    System.arraycopy(a, 0, result, 0, a.length); 
    System.arraycopy(b, 0, result, a.length, b.length); 
    return result;
} 

I wrote the following procedure for concatenation of several array:

  static public byte[] concat(byte[]... bufs) {
    if (bufs.length == 0)
        return null;
    if (bufs.length == 1)
        return bufs[0];
    for (int i = 0; i < bufs.length - 1; i++) {
        byte[] res = Arrays.copyOf(bufs[i], bufs[i].length+bufs[i + 1].length);
        System.arraycopy(bufs[i + 1], 0, res, bufs[i].length, bufs[i + 1].length);
        bufs[i + 1] = res;
    }
    return bufs[bufs.length - 1];
}

It uses Arrays.copyOf


Perhaps the easiest way:

ByteArrayOutputStream output = new ByteArrayOutputStream();

output.write(ciphertext);
output.write(mac);

byte[] out = output.toByteArray();

First you need to allocate an array of the combined length, then use arraycopy to fill it from both sources.

byte[] ciphertext = blah;
byte[] mac = blah;
byte[] out = new byte[ciphertext.length + mac.length];


System.arraycopy(ciphertext, 0, out, 0, ciphertext.length);
System.arraycopy(mac, 0, out, ciphertext.length, mac.length);

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to byte

Convert bytes to int? TypeError: a bytes-like object is required, not 'str' when writing to a file in Python3 How many bits is a "word"? How many characters can you store with 1 byte? Save byte array to file Convert dictionary to bytes and back again python? How do I get total physical memory size using PowerShell without WMI? Hashing with SHA1 Algorithm in C# How to create a byte array in C++? Converting string to byte array in C#

Examples related to bytearray

How to create bitmap from byte array? Put byte array to JSON and vice versa Byte Array to Hex String Java ByteBuffer to String Fastest way to convert Image to Byte array How to store a byte array in Javascript Conversion from byte array to base64 and back How do I print bytes as hexadecimal? How to convert image into byte array and byte array to base64 String in android? How to convert a byte array to a hex string in Java?

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?