我有兩個byte[]
陣列,其是未知的長度,並且我只是要附加一個的其它的,即所述端:追加一個字節[]到另一字節的末尾[]
byte[] ciphertext = blah;
byte[] mac = blah;
byte[] out = ciphertext + mac;
我已嘗試使用arraycopy()
,但似乎無法使其工作。
我有兩個byte[]
陣列,其是未知的長度,並且我只是要附加一個的其它的,即所述端:追加一個字節[]到另一字節的末尾[]
byte[] ciphertext = blah;
byte[] mac = blah;
byte[] out = ciphertext + mac;
我已嘗試使用arraycopy()
,但似乎無法使其工作。
使用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);
需要聲明out
作爲字節數組與等於的ciphertext
和mac
加在一起的長度的長度,並且然後使用arraycopy超過out
和mac
開始複製ciphertext
在端。
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;
}
我發現這更有用。 – Sorter 2016-05-01 16:42:50
首先,你需要分配的總長度的數組,然後使用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);
其他提供的解決方案是偉大的,當你想添加只有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();
我寫的以下過程幾種陣列的串聯:
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
P erhaps最簡單的方法:
ByteArrayOutputStream output = new ByteArrayOutputStream();
output.write(ciphertext);
output.write(mac);
byte[] out = output.toByteArray();
最簡單也許最好的支持,因爲ByteArrayBuffer似乎不推薦使用。 – pete 2017-05-25 18:49:29
的可能重複[簡單的方法來連接兩個字節數組(http://stackoverflow.com/questions/5513152/easy-way-to-concatenate-two-byte-arrays) – Ubunfu 2015-07-24 02:51:15