2010-05-28 61 views
1

我開始與下面的兩個值:添加值字節數組

finalString = "38,05,e1,5f,aa,5f,aa,d0"; 
string[] holder = finalString.Split(','); 

我循環通持有人就像這樣:

foreach (string item in holder) 
{ 
    //concatenate 0x and add the value to a byte array 
} 

在每次迭代中,我想串連一個0x使其成爲十六進制值並將其添加到字節數組中。

這就是我想要的字節數組是當我完成循環,如:

byte[] c = new byte[]{0x38,0x05,0xe1,0x5f,0xaa,0x5f,0xaa,0xd0}; 

到目前爲止,我所有的嘗試都沒有成功。有人能指引我朝着正確的方向嗎?

回答

6

您不必連接前綴「 0X」。解析文本時,此前綴用於由C#編譯器,但byte.Parse不使用它

byte[] myByteArray = new byte[holder.Length]; 
int i = 0; 
foreach (string item in holder) 
{ 
    myByteArray[i++] = byte.Parse(item, System.Globalization.NumberStyles.AllowHexSpecifier); 
} 
1

只是創建一個新的字節數組,這兩個數組放在一起的大小。然後插入一個,並將第二個插入新緩衝區。在.NET數組的大小是不可變

另一種方法是通過每個陣列中使用的類似名單,然後就循環,並將其添加

var buffer = new List<byte>(); 
foreach(var b in firstArray) buffer.Add(b); 
foreach(var b2 in secondArray) buffer.Add(b2); 

byte[] newArray = buffer.ToArray(); 
4

你可以做到這一點作爲一個班輪:

var c = holder.Select(s => byte.Parse(s, NumberStyles.AllowHexSpecifier)).ToArray(); 

c現在是一個字節數組你需要的數據。

+1

很酷的想法,但是,這樣的字節是十六進制模式解析編輯您的帖子。 – 2010-05-28 15:00:47

+0

s表示十六進制格式的值。它可能包含A到F的字母。byte.Parse需要指定格式的第二個參數。 – 2010-05-28 15:02:59

1

,這將產生字節值的基礎上,你必須用逗號分隔的十六進制值列表:

 string hex_numbers = "38,05,e1,5f,aa,5f,aa,d0"; 
    string[] hex_values = hex_numbers.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); 
    byte[] byte_array = new byte[hex_values.Length]; 
    for(int i = 0; i < hex_values.Length; i++) 
    { 
     byte_array[i] = byte.Parse(hex_values[i], System.Globalization.NumberStyles.AllowHexSpecifier); 
    }