我想打一个Byte[]
像这样的:C#如何设置0X ..在字节]
Byte[] data = { 0x10, 0x02, 0x04, 0x00, 0x00, 0x25, 0x23, 0x05, 0xb1, 0x10, 0x03 };
但我必须从用户那里得到这些。我累了Console.ReadLine和转换为int或字节或任何东西,但不工作,因为x不是一个数字。
问题是如何从用户获得0x10
或0x25
并设置为Byte[]
?
我想打一个Byte[]
像这样的:C#如何设置0X ..在字节]
Byte[] data = { 0x10, 0x02, 0x04, 0x00, 0x00, 0x25, 0x23, 0x05, 0xb1, 0x10, 0x03 };
但我必须从用户那里得到这些。我累了Console.ReadLine和转换为int或字节或任何东西,但不工作,因为x不是一个数字。
问题是如何从用户获得0x10
或0x25
并设置为Byte[]
?
可以Split
输入字符串转换成块Convert
每个块中的字节,最后兑现他们ToArray
:
// You can let user input the array as a single string
// Test/Demo; in real life it should be
// string source = Console.ReadLine();
string source = "0x10, 0x02, 0x04, 0x00, 0x00, 0x25, 0x23, 0x05, 0xb1, 0x10, 0x03";
byte[] result = source
.Split(new char[] {' ', ':', ',', ';', '\t'}, StringSplitOptions.RemoveEmptyEntries)
.Select(item => Convert.ToByte(item, 16))
.ToArray();
让我们代表阵列背面为字符串:
string test = string.Join(", ", result
.Select(item => "0x" + item.ToString("x2")));
// "0x10, 0x02, 0x04, 0x00, 0x00, 0x25, 0x23, 0x05, 0xb1, 0x10, 0x03"
Console.Write(test);
如果你想将字节保存在一个循环中,我建议你在循环之前创建一个列表作为辅助变量。
List<byte> mylist = new List<byte>();
然后你就可以扫描在命令行输入和使用这样的存储他们:
mylist.Add(Convert.ToByte(my_input, 16));
在最后你只需将列表转换为数组
mylist.ToArray();