2011-03-20 120 views
24

我有兩個byte[]陣列,其是未知的長度,並且我只是要附加一個的其它的,即所述端:追加一個字節[]到另一字節的末尾[]

byte[] ciphertext = blah; 
byte[] mac = blah; 
byte[] out = ciphertext + mac; 

我已嘗試使用arraycopy(),但似乎無法使其工作。

+1

的可能重複[簡單的方法來連接兩個字節數組(http://stackoverflow.com/questions/5513152/easy-way-to-concatenate-two-byte-arrays) – Ubunfu 2015-07-24 02:51:15

回答

49

使用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); 
+0

非常好!感謝您的快速解決方案。像魅力一樣工作,現在看起來很簡單! – Mitch 2011-03-20 14:17:06

+0

我相信如果我們事先不知道最終數組的大小,會造成困難。 – Shashwat 2017-06-06 05:50:12

12

需要聲明out作爲字節數組與等於的ciphertextmac加在一起的長度的長度,並且然後使用arraycopy超過outmac開始複製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; 
} 
+0

我發現這更有用。 – Sorter 2016-05-01 16:42:50

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); 
7

其他提供的解決方案是偉大的,當你想添加只有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(); 
3

我寫的以下過程幾種陣列的串聯:

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

8

P erhaps最簡單的方法:

ByteArrayOutputStream output = new ByteArrayOutputStream(); 

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

byte[] out = output.toByteArray(); 
+0

最簡單也許最好的支持,因爲ByteArrayBuffer似乎不推薦使用。 – pete 2017-05-25 18:49:29

相關問題