从字节 [] 中删除尾随零? [英] Remove trailing zeros from byte[]?

查看:36
本文介绍了从字节 [] 中删除尾随零?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 TCP 协议并从套接字读取并将数据写入字节 [] 数组.
这是我的数据示例:

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

我创建了一个大小为 1024 的 byte[] 数组.现在我使用这个方法从中删除空索引:

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

但它也删除了可能有用数据的 0x00 索引...
如何删除未用非零数据(尾随 0)包裹的 0?

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

推荐答案

您应该修复从 TCP 套接字读取的代码,这样您就不会读取之后打算丢弃的内容.这对我来说似乎是一种浪费.

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

这篇关于从字节 [] 中删除尾随零?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆