简体   繁体   中英

Best way to remove extra zeroes in byte array

I am making a serialization code and I´m trying to make the byte output smallest as possible.

My approach is packing zero bytes like this:

ex: D3 00 00 00 00 00 00 00 00 00 00 28 85 (12 bytes)
turns into 09(zero array length) 01 (offset) D3 28 85 (5 bytes)

My question is: There any efficient way to do this? I use a List to store and concatenate byte arrays, and the data have a "Header" to identify what kind of data the byte array are. Just stuck in this.

Suggestions?

Edit: An approach I have to this with code is:

bool start = false;
byte offsetStart = 0; 
byte offsetEnd = 0;
for(int i = 0; i < array.Length; i++)
{
    if(array[i] == 0 && !start)
    {
         offsetstart == (byte)i;
         start = true;
    } 
    else if (array[i] != 0 && start)
    {
         offsetend == (byte)i;
         start = false;
    }

    if(offsetEnd - offsetStart <= //Some length ) return array;
    else 
    {
        byte arrayLength = offsetEnd - offsetStart;
        return arrayLength + offsetStart + 
        Array.Take(offsetStart).Skip(ArrayLength).Take(array.Length - offsetEnd);

    }
}

You should go for a simple protocol. Create something like a header. For example. Start with a byte which indicates if you're starting with Zero's (0) or NonZero's (1) . Zero's will be compressed, non-zero's not. So the first byte will be a zero or one. The second byte contains the count. If it were zero's, just write nothing, if it were non-zero's the values will be behind it.

Example:

[0][10][1][10]1234567891[0][10]
[0][9][1][12]123456789123[0][9]

So when decompressing:

[0][10] means, add 10 zero's, 
[1][10]1234567891 means, add 10 non-zero's, followed by the values
[0][9]  means, add 9 zero's, 
[1][12]123456789123 means,add 12 non-zero's, followed by the values

This way the zero's aren't "saved". It is easily to compress and decompress.

If you have some difficulty writing the code, i'll add some.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM