2011-03-20 61 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

相关问题