从字节[512]中删除额外00-00-00-00-00的最佳方法是什么?
目前,当我从接收到的非512字节数据包中加载一些数据时,它会返回类似
的内容 Byte[] received = new Byte[512];
int Recieving = Sockitty.ReceiveFrom(received, ref endPoint132);
string dataReceived = BitConverter.ToString(received);
txtReceived.AppendText(dataReceived);
//Outputs the following
74 68 69 73 20 69 73 20 61
20 74 65 73 74 00 68 65 6c
6c 6f 20 00 68 65 72 65 2e
**00** 00 00 00 00 00 00 00 00 //This is the part that needs to be removed but the stared 00.
00 00 00 00 00 00 00 00 00
00 00 00 00 00 00 00 00 00 ... and so on
我怎样才能删除最后一个00?正如你所看到的,数据包本身内部有00,我不想删除。
最好的方法是反转然后循环直到它遇到00以外的其他东西,然后从那时加载到新的字节数组?我怎么知道要加载它的数组的大小?
我很困惑。任何帮助赞赏。谢谢!
答案 0 :(得分:7)
Socket.ReceiveFrom
的这个重载返回读入数组的字节数;尊重数组内容到这个长度,或者,如果你真的需要,将数组的大小调整到这个长度。
答案 1 :(得分:3)
您可以从末尾查找第一个非零值,然后将该数据复制到新数组:
int len = 512;
while (len > 0 && received[len - 1] == 0) {
len--;
}
{
byte[] cropped = new byte[len];
if (len > 0) {
Array.Copy(received, 0, cropped, 0, len);
}
received = cropped;
如果可能,您应该尝试找出数据的实际大小,而不是寻找非零值。数据可能在末尾包含零值,不应删除。
ReceiveFrom
方法返回您在缓冲区中收到的字节数,因此您应该使用它:
byte[] received = new Byte[512];
int len = Sockitty.ReceiveFrom(received, ref endPoint132);
byte[] cropped = new byte[len];
Array.Copy(received, 0, cropped, 0, len);
received = cropped;
答案 2 :(得分:3)
你可以简单地通过linq:
来做到这一点received = received.Reverse().SkipWhile(x => x == 0).Reverse().ToArray();
因为您的输入大小很小,所以没有性能问题,除非您在很短的时间内调用太多(在这种情况下,您可以正常迭代数组)。但我认为你的收到比这部分代码更耗时。
编辑:对于您的评论案例,请执行以下操作:
received = received.Reverse()
.SkipWhile((x,i) => x == 0 && received[512 - i - 2] == 0).Reverse().ToArray();
答案 3 :(得分:0)
byte[] buf;
...
int length;
for(length = buf.length -1; i--; (i>=0) && buf[length] == 0)
continue;
byte[] cleanData = new byte[++length];
Array.Copy(buf, 0, cleanData, 0, length);
答案 4 :(得分:0)
byte[] getclear()
{
int length = 512;
int first_nonzero_reversed = 0;
byte[] received = new byte[length];
//get data
for (int i = length - 1; i >= 0; i--)
{
if (received[i] != 0)
{
first_nonzero_reversed = i;
break;
}
}
byte[] target = new byte[first_nonzero_reversed + 1];
Array.Copy(received, target, target.Length);
return target;
}