C#字节字符串转换为字节数组

10
我有以下字节串
17 80 41 00 01 00 01 00 08 00 44 61 72 65 46 61 74 65 01 00 00 00 01 00 03 00 01 00 09 00 43 68 61 6E 6E 65 6C 2D 31 00 00 02 00 09 00 43 68 61 6E 6E 65 6C 2D 32 65 00 03 00 09 00 43 68 61 6E 6E 65 6C 2D 33 65 00
如何最好地将它作为用户输入并转换为字节数组?
3个回答

14

尝试:

string text = ...
byte[] bytes = text.Split()
                   .Select(t => byte.Parse(t, NumberStyles.AllowHexSpecifier))
                   .ToArray();

如果您想仅在空格字符上进行拆分(而不是任何空白符),请使用Split(' ')

+1 这就是我写的“全能版”,非常简洁,但容易让人感到困惑。 - joe_coolish

8
如果用户像这样在命令行中输入,请执行以下操作:
        string input = GetInput(); // this is where you get the input
        string[] numbs = input.Split(' ');
        byte[] array = new byte[numbs.Length];
        int i = 0;

        foreach (var numb in numbs)
        {
            array[i++] = byte.Parse(numb, NumberStyles.HexNumber);
        }

1

您可以使用 System.Byte 中的 Parse 方法来解析单个十六进制对:

// Get the string from the user
string s=Console.ReadLine();

// Convert to a byte array
byte[] sBytes=s.Split(new char[] {' '})
               .Select(hexChar => byte.Parse(hexChar,NumberStyles.HexNumber))
               .ToArray();

// *** Test code follows ***

// Display the bytes (optional), to verify that the conversion worked
StringBuilder hexString=new StringBuilder(sBytes.Length*3);

foreach (byte b in sBytes)     
{
  // Separate hex pairs with a space
  if (hexString.Length>0)
    hexString.Append(' ');
  // Append next hex pair (i.e., formatted byte)
  hexString.AppendFormat("{0:x2}",b);
}

Console.WriteLine(hexString);

3
Encoding.ASCII功能是将ASCII字符串转换为字节,而不是将十六进制格式的字符串转换为字节。 - Iain
我想我对问题的理解有些困难。现在我更新了我的代码,因为我认为我理解了问题作者的意图。 - Michael Goldshteyn

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接