字节数组结尾空字节填充:如何有效地复制到较小的字节数组 [英] Byte array with padding of null bytes at the end: how to efficiently copy to smaller byte array

查看:253
本文介绍了字节数组结尾空字节填充:如何有效地复制到较小的字节数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有:

<$p$p><$c$c>[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)的一个新的数组并在复制这些字节?注:我不知道有多少空字节,或值字节会有


解决方案

下面是我的尝试:

 字节的静态[] TRIM(字节[]字节)
{
    INT I = bytes.length - 1;
    而(I&GT; = 0&放大器;&安培;字节[I] == 0)
    {
         - 一世;
    }    返回Arrays.copyOf(字节,1 + 1);
}公共静态无效的主要(字串[] args)
{
    字节[]字节= {0,1,2,0,3,4,5,0,6,0,0,7,8,9,10,0,0,0,0};    字节[] =修剪修剪(字节);    返回;
}

Have:

[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]

Want:

[46][111][36][11][101][55][87][30][122][75][66][32][49][55][67][77][88]

I have an array of bytes size 8192 to start, and starting at some index in that first array until the end of the array the bytes are all null bytes. So there might be 6000 bytes with values and 2196 null bytes at the end in the array. How do I efficiently create a new array of size (6000) and copy those bytes over? Note: I do not know how many null bytes, or bytes with values there will be.

解决方案

Here is my try:

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;
}

这篇关于字节数组结尾空字节填充:如何有效地复制到较小的字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆