Byte array with padding of null bytes at the end: how to efficiently copy to smaller byte array

十年热恋 提交于 2019-12-20 11:34:31

问题


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.


回答1:


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



回答2:


why not try the static method array copy in the system class just give the source array src start position , destination array , destination start position and the length

        System.arraycopy(src, srcPos, dest, destPos, length);
        byte [] dest= new byte [6000];
        System.arraycopy(src, 0, dest, 0, 6000);



回答3:


I think we can do in this way also

byte []array={0, 69, 0, 71, 0, 72};

byte ar[]=new String(array).replaceAll("\0", "").getBytes();



回答4:


With kotlin :

val strWithoutZeros = String(byteArray,StandardCharsets.UTF_8).replace(0.toChar().toString(), "")

val byteArrayWithoutZeros = strWithoutZeros.toByteArray(StandardCharsets.UTF_8)


来源:https://stackoverflow.com/questions/17003164/byte-array-with-padding-of-null-bytes-at-the-end-how-to-efficiently-copy-to-sma

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!