C# 是否从字节[]中删除尾随的零?
我正在使用TCP协议,从套接字读取数据,并将数据写入字节[]数组。 以下是我的数据示例:C# 是否从字节[]中删除尾随的零?,c#,arrays,byte,C#,Arrays,Byte,我正在使用TCP协议,从套接字读取数据,并将数据写入字节[]数组。 以下是我的数据示例: 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[]数组。现在,我使用此方法从中删除空索引: public void Decode(byte[] packet) { byte[] temp
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[]数组。现在,我使用此方法从中删除空索引:
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?您应该修复从TCP套接字读取的代码,这样您就不会读取以后要丢弃的内容。对我来说这似乎是浪费 但要回答您的问题,您可以开始反向计数,直到遇到非零字节。确定此非零字节的索引后,只需从源阵列复制到目标阵列:
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;
}
由于不能根据定义缩小数组的大小,因此必须使用动态数据结构 以列表为例
List<byte> byteList;
那么您想在末尾修剪0x00s并将其复制到新阵列中?这将是:
int endIndex = packet.Length - 1;
while (endIndex >= 0 && packet[endIndex] == 0)
endIndex--;
byte[] result = new byte[endIndex + 1];
Array.Copy(packet, 0, result, 0, endIndex + 1);
当然,最后也可能有有效的0x00s。实际上,MSDN站点上给出了非常接近的示例。真正的C4.5风格-带谓词。虽然已经提交了正确的答案,但如果您愿意,您可以尝试一下
另外,我仍在等待Linq风格的答案,末尾带有Select and.ToList这是一个非常短且快速的函数,用于从数组中修剪尾随的零
public static byte[] TrimEnd(byte[] array)
{
int lastIndex = Array.FindLastIndex(array, b => b != 0);
Array.Resize(ref array, lastIndex + 1);
return array;
}
有一个很好的单线解决方案纯LINQ:
public static byte[] TrimTailingZeros(this byte[] arr)
{
if (arr == null || arr.Length == 0)
return arr;
return arr.Reverse().SkipWhile(x => x == 0).Reverse().ToArray();
}
你怎么知道零是否有用?空索引是什么意思?@harold,因为顺序对我来说非常重要…数组中的索引不能为空。由于byte是值类型,因此两个值都不相同。是否要从数组中删除0x00值?当字节[]被填充时,您应该在某处获得一个值,告诉您读取了多少字节。这可能是当前被忽略的读取方法的返回值。您应该使用它来调整数组的大小,而不是从末尾修剪0。这将在第一个0字节处停止,并可能在之后修剪非零字节。OP只想删除数组末尾的连续零字节。当然你是对的:但我不会删除帖子,也许这会让他知道如何使用列表。。
public static byte[] TrimEnd(byte[] array)
{
int lastIndex = Array.FindLastIndex(array, b => b != 0);
Array.Resize(ref array, lastIndex + 1);
return array;
}
Byte[] b = new Byte[1024]; // Array of 1024 bytes
List<byte> byteList; // List<T> of bytes
// TODO: Receive bytes from TcpSocket into b
foreach(var val in b) // Step through each byte in b
{
if(val != '0') // Your condition
{
}
else
{
bytelist.Add(val); //Add the byte to the List
}
}
bytelist.ToArray(); // Convert the List to an array of bytes
public static byte[] TrimTailingZeros(this byte[] arr)
{
if (arr == null || arr.Length == 0)
return arr;
return arr.Reverse().SkipWhile(x => x == 0).Reverse().ToArray();
}