2011-07-31 233 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)); 
相关问题