Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#字节字符串到字节数组_C#_Arrays_Byte - Fatal编程技术网

C#字节字符串到字节数组

C#字节字符串到字节数组,c#,arrays,byte,C#,Arrays,Byte,我有以下字节串 17 80 41 00 01 00 01 00 08 00 44 61 72 65 46 61 74 65 01 00 00 00 00 00 00 00 00 00 00 00 00 00 09 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00

我有以下字节串

17 80 41 00 01 00 01 00 08 00 44 61 72 65 46 61 74 65 01 00 00 00 00 00 00 00 00 00 00 00 00 00 09 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00


将其作为用户输入并放入字节数组的最佳方法是什么?

您可以使用System.byte中的解析方法来解析各个hax对:

// 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);
尝试:


如果您只想分割空格字符(而不是任何空格),请使用
split(“”)

如果用户正在将其输入命令行,请执行以下操作:

        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这是我写的文章中的“一体”部分。非常简洁,但可能会让人困惑。Encoding.ASCII不是从ASCII字符串转换为字节,而不是从十六进制格式的字符串转换为字节吗?我想我理解这个问题有困难。我已经更新了我的代码,现在我想我明白了问题作者的意图。
        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);
        }