java – 将byte []附加到另一个byte [] 的末尾

参见英文答案 > Easy way to concatenate two byte arrays                                    12个
我有两个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);
上一篇:java 11 不可修改集合API


下一篇:System.arraycopy() 数组复制