C# 将字节数组中的 ASCII 转换为字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18627304/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert ASCII in a byte array to string
提问by frog_jr
I seem to be having problems with my string conversions in C#. My application has received a byte array consisting of an ASCII string (one byte per character). Unfortunately it also has a 0 in the first location. So how do I convert this byte array to a c# string? Below is a sample of the data I am trying to convert:
我在 C# 中的字符串转换似乎有问题。我的应用程序收到了一个由 ASCII 字符串(每个字符一个字节)组成的字节数组。不幸的是,它的第一个位置也有一个 0。那么如何将这个字节数组转换为 ac# 字符串呢?以下是我尝试转换的数据示例:
byte[] exampleByteArray = new byte[] { 0x00, 0x52, 0x50, 0x4D, 0x20, 0x3D, 0x20, 0x32, 0x35, 0x35, 0x2C, 0x36, 0x30, 0x0A, 0x00 };
string myString = null;
I have made several unsuccessful attempts, so thought I would ask for assistance. Eventually I need to add the string to a listbox:
我做了几次不成功的尝试,所以我想寻求帮助。最终我需要将字符串添加到列表框:
listBox.Items.Add(myString);
The desired output in the listBox: "RPM = 255,630" (with or without the linefeed). The byte array will be variable length, but will always be terminated with 0x00
列表框中所需的输出:“RPM = 255,630”(带或不带换行符)。字节数组将是可变长度的,但总是以 0x00 结尾
采纳答案by Damith
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();
Result :
结果 :
RPM = 255,60
转速 = 255,60
you can add this to listBox
你可以把这个添加到 listBox
listBox.Items.Add(myString);
Update :
更新 :
As per new comment byte array can contain garbage after the trailing 0x00 (remnants of previous strings).
根据新的注释, 字节数组在尾随 0x00(先前字符串的残余部分)之后可能包含垃圾。
You need to skip first 0x00
and then consider bytes until you get 0x00
, so you can use power of Linq to do this task. e.g ASCII.GetString(exampleByteArray.Skip(1).TakeWhile(x => x != 0x00).ToArray())
您需要先跳过0x00
,然后再考虑字节,直到得到0x00
,因此您可以使用 Linq 的强大功能来完成此任务。例如ASCII.GetString(exampleByteArray.Skip(1).TakeWhile(x => x != 0x00).ToArray())
回答by clamchoda
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);
Result: myString = "\0RPM = 255,60\n\0"
结果: myString = "\0RPM = 255,60\n\0"
回答by Rodrick Chapman
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));