Mit*_*tch 30 java byte bytearray arraycopy
我有两个byte[]长度未知的数组,我只想将一个附加到另一个的末尾,即:
byte[] ciphertext = blah;
byte[] mac = blah;
byte[] out = ciphertext + mac;
Run Code Online (Sandbox Code Playgroud)
我试过使用arraycopy()但似乎无法让它工作.
kro*_*ock 61
使用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);
Run Code Online (Sandbox Code Playgroud)
小智 24
也许最简单的方法:
ByteArrayOutputStream output = new ByteArrayOutputStream();
output.write(ciphertext);
output.write(mac);
byte[] out = output.toByteArray();
Run Code Online (Sandbox Code Playgroud)
Mus*_*sis 16
您需要声明out一个长度等于长度ciphertext并mac加在一起的字节数组,然后使用arraycopy 复制ciphertext开头out和mac结尾.
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;
}
Run Code Online (Sandbox Code Playgroud)
当你想只添加2个字节数组时,其他提供的解决方案很棒,但如果你想继续添加几个byte []块来制作一个:
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();
Run Code Online (Sandbox Code Playgroud)
首先,您需要分配组合长度的数组,然后使用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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
97341 次 |
| 最近记录: |