2017-01-23 76 views
1

我想打一個Byte[]像這樣的:C#如何設置0X ..在字節]

Byte[] data = { 0x10, 0x02, 0x04, 0x00, 0x00, 0x25, 0x23, 0x05, 0xb1, 0x10, 0x03 }; 

但我必須從用戶那裏得到這些。我累了Console.ReadLine和轉換爲int或字節或任何東西,但不工作,因爲x不是一個數字。

問題是如何從用戶獲得0x100x25並設置爲Byte[]

回答

3

可以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); 
1

如果你想將字節保存在一個循環中,我建議你在循環之前創建一個列表作爲輔助變量。

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

然後你就可以掃描在命令行輸入和使用這樣的存儲他們:

mylist.Add(Convert.ToByte(my_input, 16)); 

在最後你只需將列表轉換爲數組

mylist.ToArray();