Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
741 views
in Technique[技术] by (71.8m points)

c# - Remove trailing zeros from 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)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...