Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove trailing zeros from byte[]?

Tags:

arrays

c#

byte

I'm working with TCP protocol and read from socket and write the data to a byte[] array.
Here is a example of my data:

94 39 E5 D9 32 83
D8 5D 4C B1 CB 99 
08 00 45 00 00 98 
41 9F 40 00 6C 06 
9C 46 26 50 48 7D 
C0 A8 01 05 03 28

I created a byte[] array with size of 1024. Now I use this method to remove null indexes from it:

public void Decode(byte[] packet)
{
    byte[] temp;
    int c = 0;
    foreach(byte x in packet)
        if (x != 0)
            c++;
    temp = new byte[c];
    for (int i = 0; i < c; i++)
        temp[i] = packet[i];
    MessageBox.Show(temp.Length.ToString());
}

But it removes also 0x00 indexes that it maybe useful data...
How can I remove the 0s that are not wrapped with non-zero data (trailing 0s)?

like image 873
Soroush Khosravi Avatar asked Jun 29 '12 14:06

Soroush Khosravi


2 Answers

This is quite short and fast function to trim trailing zeroes from array.

public static byte[] TrimEnd(byte[] array)
{
    int lastIndex = Array.FindLastIndex(array, b => b != 0);

    Array.Resize(ref array, lastIndex + 1);

    return array;
}
like image 68
nefarel Avatar answered Sep 30 '22 18:09

nefarel


You should fix the code that's reading from the TCP socket so that you don't read something that you intend to throw away afterwards. It seems like a waste to me.

But to answer your question you could start counting in reverse order until you encounter a non-zero byte. Once you have determined the index of this non-zero byte, simply copy from the source array to the target array:

public byte[] Decode(byte[] packet)
{
    var i = packet.Length - 1;
    while(packet[i] == 0)
    {
        --i;
    }
    var temp = new byte[i + 1];
    Array.Copy(packet, temp, i + 1);
    MessageBox.Show(temp.Length.ToString());
    return temp;
}
like image 34
Darin Dimitrov Avatar answered Sep 30 '22 18:09

Darin Dimitrov