连接两个字节数组的简单方法是什么?
Say,
byte a[];
byte b[];
我如何连接两个字节数组,并将其存储在另一个字节数组?
连接两个字节数组的简单方法是什么?
Say,
byte a[];
byte b[];
我如何连接两个字节数组,并将其存储在另一个字节数组?
当前回答
byte[] result = new byte[a.length + b.length];
// copy a to result
System.arraycopy(a, 0, result, 0, a.length);
// copy b to result
System.arraycopy(b, 0, result, a.length, b.length);
其他回答
最简单的:
byte[] c = new byte[a.length + b.length];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, a.length, b.length);
byte[] result = new byte[a.length + b.length];
// copy a to result
System.arraycopy(a, 0, result, 0, a.length);
// copy b to result
System.arraycopy(b, 0, result, a.length, b.length);
这就是我的方法!
public static byte[] concatByteArrays(byte[]... inputs) {
int i = inputs.length - 1, len = 0;
for (; i >= 0; i--) {
len += inputs[i].length;
}
byte[] r = new byte[len];
for (i = inputs.length - 1; i >= 0; i--) {
System.arraycopy(inputs[i], 0, r, len -= inputs[i].length, inputs[i].length);
}
return r;
}
特点:
使用varargs(…)来调用任意数量的字节[]。 使用System.arraycopy(),它是由机器特定的本机代码实现的,以确保高速运行。 创建一个新字节[],其大小与所需要的大小一致。 通过重用i和len变量来分配更少的int变量。 与常数比较更快。
请记住:
更好的方法是复制@Jonathan代码。问题来自本地变量数组,因为当此数据类型传递给另一个函数时,Java会创建新的变量。
下面是一个很好的解决方案,使用Guava的com.google.common.primitives.Bytes:
byte[] c = Bytes.concat(a, b);
这个方法的伟大之处在于它有一个varargs签名:
public static byte[] concat(byte[]... arrays)
这意味着您可以在单个方法调用中连接任意数量的数组。
另一种方法是使用一个实用函数(如果你喜欢,你可以让它成为一个通用实用类的静态方法):
byte[] concat(byte[]...arrays)
{
// Determine the length of the result array
int totalLength = 0;
for (int i = 0; i < arrays.length; i++)
{
totalLength += arrays[i].length;
}
// create the result array
byte[] result = new byte[totalLength];
// copy the source arrays into the result array
int currentIndex = 0;
for (int i = 0; i < arrays.length; i++)
{
System.arraycopy(arrays[i], 0, result, currentIndex, arrays[i].length);
currentIndex += arrays[i].length;
}
return result;
}
像这样调用:
byte[] a;
byte[] b;
byte[] result = concat(a, b);
它也可以用于连接3,4,5个数组等。
这样做可以获得快速arraycopy代码的优势,而且非常易于阅读和维护。