How to concatenate two byte arrays in Java?

Asked

Viewed 1,394 times

4

I have:

byte mensagem[];
byte nonce[];

How do I concatenate the array nonce at the end of the array mensagem and store in a third array?

4 answers

4

2

Try it like this:

byte [] terceiro = new byte[mensagem.length + nonce.length];
for (int i = 0; i < terceiro.length; i++) {
    if (i < mensagem.length) {
        terceiro[i] = mensagem[i];
    } else {
        terceiro[i] = nonce[i - mensagem.length];
    }
}
  • It worked, but I had to make some modifications. Can I edit your reply? You forgot to put the += for example.

  • There is a bug in this code. When the int value is >9 (ie 10) it gives indexOutBoundsException. I believe he’s trying to put 2 bytes and it doesn’t fit.

  • 1

    @Avelino At his suggestion, nonce[msg.length - i] will not be negative?

  • So, the first solution of Piovezan did not work. I made some modifications, but only works until the 9, going from this gives error. Was it just the += that was wrong? (Gave indexOfBoundsException -1)

  • I tested the example and it looks ok. And it’s not necessary += because there is no string being concatenated, the code only works with arrays.

2


One way to do this is to store them in one ByteArrayOutputStream:

byte[] primeiroArray = "stack".getBytes();
byte[] segundoArray  = "overflow".getBytes();
ByteArrayOutputStream terceiroArray = new ByteArrayOutputStream();

terceiroArray.write(primeiroArray);
terceiroArray.write(segundoArray);

System.out.println(Arrays.toString(terceiroArray.toByteArray()));
System.out.println(terceiroArray.toString());

// [115, 116, 97, 99, 107, 111, 118, 101, 114, 102, 108, 111, 119]
// stackoverflow

See demonstração

Another possibility is to use the function ArrayUtils.addAll() library Apache Commons Lang:

byte[] terceiroArray = ArrayUtils.addAll(primeiroArray, segundoArray);
  • 1

    stack overflow. Nice example :)

2

byte [] terceiro = new byte[mensagem.length + nonce.length];

for (int i = 0; i < mensagem.length; i++) {
    terceiro[i] = mensagem[i];
}
for (int i = mensagem.length; i < terceiro.length; i++) {
    terceiro[i] = nonce[i - mensagem.length];
}

I declared the third array with capacity equal to the sum of the size of the previous two.

In the first loop I filled the third array with the bytes of the first array.

In the second loop I initialized an index for the third array at the position equal to the last index of the first array + 1. And from this index I started copying the items from the first array.

  • This solution at the end is the same as @Piovezan but uses a loop instead of IF; for those, like me, who don’t like Ifs very much :-)

  • All right, that makes it easier to understand. :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.