有:
[46][111][36][11][101][55][87][30][122][75][66][32][49][55][67][77][88][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0]
想要:
[46][111][36][11][101][55][87][30][122][75][66][32][49][55][67][77][88]
我有一个大小为 8192 的字节数组开始,并从第一个数组中的某个索引开始,直到数组结束,这些字节都是空字节。因此,数组末尾可能有 6000 个字节的值和 2196 个空字节。如何有效地创建一个新的大小数组(6000)并复制这些字节?注意:我不知道会有多少空字节,或者有值的字节。
最佳答案
这是我的尝试:
static byte[] trim(byte[] bytes)
{
int i = bytes.length - 1;
while (i >= 0 && bytes[i] == 0)
{
--i;
}
return Arrays.copyOf(bytes, i + 1);
}
public static void main(String[] args)
{
byte[] bytes = { 0, 1, 2, 0, 3, 4, 5, 0, 6, 0, 0, 7, 8, 9, 10, 0, 0, 0, 0 };
byte[] trimmed = trim(bytes);
return;
}
关于java - 在末尾填充空字节的字节数组 : how to efficiently copy to smaller byte array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17003164/