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)?
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: