Removing trailing nulls from byte array in C#

前端 未结 10 2036
感情败类
感情败类 2020-12-30 03:01

Ok, I am reading in dat files into a byte array. For some reason, the people who generate these files put about a half meg\'s worth of useless null bytes at the end of the

10条回答
  •  悲&欢浪女
    2020-12-30 03:05

    I agree with Jon. The critical bit is that you must "touch" every byte from the last one until the first non-zero byte. Something like this:

    byte[] foo;
    // populate foo
    int i = foo.Length - 1;
    while(foo[i] == 0)
        --i;
    // now foo[i] is the last non-zero byte
    byte[] bar = new byte[i+1];
    Array.Copy(foo, bar, i+1);
    

    I'm pretty sure that's about as efficient as you're going to be able to make it.

提交回复
热议问题