2011-07-31 235 views
0

可能重複:
How do you convert Byte Array to Hexadecimal String, and vice versa, in C#?字符串轉換爲字節數組

是否possbile爲一個字符串的內容轉換成完全相同的方式爲一個字節數組?

例如:我有這樣的字符串:

string strBytes="0xab, 0xcd, 0xef, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x01, 0x23, 0x45, 0x67, 0x89"; 

有沒有可以給我下面的結果,如果我通過strBytes它的任何功能。

Byte[] convertedbytes ={0xab, 0xcd, 0xef, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x01, 0x23, 0x45, 0x67, 0x89}; 
+0

這_question_包含一個函數來做到這一點。 http://stackoverflow.com/q/6889400/60761 –

回答

0
string strBytes="0xab, 0xcd, 0xef, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x01, 0x23, 0x45, 0x67, 0x89"; 

string[] toByteList = strBytes.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntires); 

byte[] converted = new byte[toByteList.Length]; 

for (int index = 0; index < toByteList.Length; index++) 
{ 
    converted[index] = Convert.ToByte(toByteList[index], 16);//16 means from base 16 
} 
1

有沒有內置的方式,但是你可以使用LINQ來做到這一點:

byte[] convertedBytes = strBytes.Split(new[] { ", " }, StringSplitOptions.None) 
           .Select(str => Convert.ToByte(str, 16)) 
           .ToArray(); 
+1

儘管在提問者代碼中的格式看起來足夠嚴格,但確實可以在逗號後加上空格 – sll

+0

@sll。但是,從您的答案複製修復將不公平,是嗎? ;) –

+0

你是對的:) – sll

0
string strBytes = "0xab, 0xcd, 0xef, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x01, 0x23, 0x45, 0x67, 0x89"; 

IEnumerable<byte> bytes = strBytes.Split(new [] {','}).Select(x => Convert.ToByte(x.Trim(), 16)); 
相關問題