将List <byte>转换为textBox.text

时间:2015-08-30 13:16:20

标签: c#

我有一个名单声明为:

List<byte> localData = new List<byte>();

该列表包含:AA 01 53 54 41 43 4B 20 4F 56 45 52 46 4C 4F 57 34 5C,其中localData[2]localData[15]我有文本STACK OVERFLOW,我将输出到文本框。

我找不到一个转换器来为我做这个,因此我使用表格以这种方式转换它:

//Here i have all printable ascii chars.
char[] asciiTable = {' ','!','"','#','$','%','&','\'','(',')'etc... }; 

打印我使用的数据:

textBox1.Clear();
for (i = 2; i < 16; i++)
{
     textBox1.Text += asciiTable[localData[i] - 32];
}

但我认为必须有更好的转换方法。注意:我正在使用Visual Studio 2015 Express for Desktop。

修改:建议的重复How to convert byte[] to string?不包括使用列表。

4 个答案:

答案 0 :(得分:2)

你可能想要

textBox1.Text =
    System.Text.Encoding.Default.GetString(localData.ToArray());

Encoding.Default为您的系统提供默认的ANSI编码。不要将此与ASCII混淆,后者是7位编码。 ANSI编码是8位编码,但前127个代码点与ASCII编码相同。

答案 1 :(得分:2)

如果你真的只需要ASCII,而且你的列表中只有一个子范围,那么你可以这样做:

List<byte> localData = new List<byte> { 0xAA, 0x01, 0x53, 0x54, 0x41, 0x43, 0x4B, 0x20, 0x4F, 0x56, 0x45, 0x52, 0x46, 0x4C, 0x4F, 0x57, 0x34, 0x5C };
textBox1.Text = Encoding.ASCII.GetString(localData.GetRange(2, 14).ToArray());

如果您需要支持ASCII范围之外的字符的转换,只需更改代码段即可使用相应的Encoding属性。

答案 2 :(得分:1)

使用LINQ的解决方案:

List<byte> localData = new List<byte> { 0xAA, 0x01, 0x53, 0x54, 0x41, 0x43, 0x4B, 0x20, 0x4F, 0x56, 0x45, 0x52, 0x46, 0x4C, 0x4F, 0x57, 0x34, 0x5C };

string txt = new string(localData.Where((b, index) => index >= 2 && index <= 15)
                                 .Select(b => (char)b).ToArray());

WriteLine(txt); // STACK OVERFLOW

答案 3 :(得分:0)

System.Text.Encoding课程。它具有一些用于编码和解码文本的属性。应该有一个属性Default,它提供默认编码(在大多数情况下足够)。

GetString方法,它接受一个字节数组。见https://msdn.microsoft.com/en-us/library/744y86tc(v=vs.110).aspx

您可以在字节集合上调用ToArray,然后将其提供给GetString

来自MSDN的示例

private static string ReadFromBuffer(FileStream fStream)
{
    Byte[] bytes = new Byte[MAX_BUFFER_SIZE];
    string output = String.Empty;
    Decoder decoder8 = enc8.GetDecoder();

    while (fStream.Position < fStream.Length) {
       int nBytes = fStream.Read(bytes, 0, bytes.Length);
       int nChars = decoder8.GetCharCount(bytes, 0, nBytes);
       char[] chars = new char[nChars];
       nChars = decoder8.GetChars(bytes, 0, nBytes, chars, 0);
       output += new String(chars, 0, nChars);                                                     
    }
    return output;
}