在Java中,如何从byte[]数组中删除前16个字节?我知道可能需要通过将数组复制到新数组来完成此操作。如果有示例或帮助,将不胜感激。
请参阅Java库中的Arrays
类:https://docs.oracle.com/javase/9/docs/api/java/util/Arrays.html#copyOfRange-byte:A-int-int-
Arrays.copyOfRange(byte[] original, int from, int to)
from
表示包含,而 to
表示不包含。它们都是以零为基础的索引,因此要删除前16个字节,请执行以下操作:
Arrays.copyOfRange(original, 16, original.length);
byte[] a;
...
if(a.length > 1) {
byte[] newA = new byte[a.length-2];
for(int i = 2; i < a.length; ++i)
newA[i-2]=a[i];
}
void remove(byte[] b)
{
for(i=16;i<b.length;i++)
{
a[i-16]=b[i];
Process... arrays
}
}
System.arraycopy()
也可以做到这一点:
public static byte[] truncate(byte[] bytes, int srcPos, int newLength) {
if (bytes.length < newLength) {
return bytes;
} else {
byte[] truncated = new byte[newLength];
System.arraycopy(bytes, srcPos, truncated, 0, newLength);
return truncated;
}
}