Добавление байта [] в конец другого байта []
У меня есть два массива byte[]
, которые имеют неизвестную длину, и я просто хочу добавить один к концу другого, т.е.
byte[] ciphertext = blah;
byte[] mac = blah;
byte[] out = ciphertext + mac;
Я попытался использовать arraycopy()
, но не могу заставить его работать.
Ответы
Ответ 1
Используя System.arraycopy()
, должно работать следующее:
// 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);
Ответ 2
Вам нужно объявить out
как массив байтов с длиной, равной длине ciphertext
и mac
, добавленной вместе, а затем скопировать ciphertext
в начале out
и mac
over конец, используя 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;
}
Ответ 3
Другие предоставленные решения великолепны, если вы хотите добавить только 2 байтовых массива, но если вы хотите сохранить несколько байтов [] кусков, чтобы сделать один:
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();
Ответ 4
Возможно, самый простой способ:
ByteArrayOutputStream output = new ByteArrayOutputStream();
output.write(ciphertext);
output.write(mac);
byte[] out = output.toByteArray();
Ответ 5
Сначала вам нужно выделить массив объединенной длины, а затем использовать arraycopy, чтобы заполнить его из обоих источников.
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);
Ответ 6
Я написал следующую процедуру для конкатенации нескольких массивов:
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];
}
Он использует Arrays.copyOf