将字节数组中的ASCII转换为字符串

我似乎在C#中使用字符串转换时出现问题。 我的应用程序收到一个由ASCII字符串组成的字节数组(每个字符一个字节)。 不幸的是,它在第​​一个位置也有0。 那么如何将这个字节数组转换为ac#string呢? 以下是我要转换的数据示例:

byte[] exampleByteArray = new byte[] { 0x00, 0x52, 0x50, 0x4D, 0x20, 0x3D, 0x20, 0x32, 0x35, 0x35, 0x2C, 0x36, 0x30, 0x0A, 0x00 }; string myString = null; 

我做了几次不成功的尝试,所以我想请求帮助。 最终我需要将字符串添加到列表框中:

 listBox.Items.Add(myString); 

listBox中的所需输出:“RPM = 255,630”(带或不带换行符)。 字节数组的长度可变,但始终以0x00结尾

 byte[] exampleByteArray = new byte[] { 0x00, 0x52, 0x50, 0x4D, 0x20, 0x3D, 0x20, 0x32, 0x35, 0x35, 0x2C, 0x36, 0x30, 0x0A, 0x00 }; exampleByteArray = exampleByteArray.Where(x=>x!=0x00).ToArray(); // not sure this is OK with your requirements string myString = System.Text.Encoding.ASCII.GetString(exampleByteArray).Trim(); 

结果:

RPM = 255,60

你可以将它添加到listBox

 listBox.Items.Add(myString); 

更新:

根据新注释, 字节数组可以在尾随0x00之后包含垃圾(前一个字符串的残余)。

您需要先跳过0x00然后考虑字节,直到得到0x00 ,这样您就可以使用Linq的function来执行此任务。 例如ASCII.GetString(exampleByteArray.Skip(1).TakeWhile(x => x != 0x00).ToArray())

  byte[] exampleByteArray = new byte[] { 0x00, 0x52, 0x50, 0x4D, 0x20, 0x3D, 0x20, 0x32, 0x35, 0x35, 0x2C, 0x36, 0x30, 0x0A, 0x00 }; string myString = System.Text.ASCIIEncoding.Default.GetString(exampleByteArray); 

结果: myString = "\0RPM = 255,60\n\0"

 var buffer = new byte[] { 0x00, 0x52, 0x50, 0x4D, 0x20, 0x3D, 0x20, 0x32, 0x35, 0x35, 0x2C, 0x36, 0x30, 0x0A, 0x00 } .Skip(1) .TakeWhile(b => b != 0x00).ToArray(); Console.WriteLine(System.Text.Encoding.ASCII.GetString(buffer));