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

前端 未结 4 458
独厮守ぢ
独厮守ぢ 2020-12-28 16:17

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]

相关标签:
4条回答
  • 2020-12-28 16:20

    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();
    
    0 讨论(0)
  • 2020-12-28 16:20

    With kotlin :

    val strWithoutZeros = String(byteArray,StandardCharsets.UTF_8).replace(0.toChar().toString(), "")
    
    val byteArrayWithoutZeros = strWithoutZeros.toByteArray(StandardCharsets.UTF_8)
    
    0 讨论(0)
  • 2020-12-28 16:28

    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);
    
    0 讨论(0)
  • 2020-12-28 16:32

    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;
    }
    
    0 讨论(0)
提交回复
热议问题