本文介绍了将字节数组中的ASCII转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

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

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

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

推荐答案

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

结果:

您可以将其添加到 listBox

listBox.Items.Add(myString);

更新:

根据新评论字节数组在尾随0x00(先前字符串的剩余字符)之后可以包含垃圾。

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

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

这篇关于将字节数组中的ASCII转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 21:56