关于c#:将字符串转换为字节数组

convert string to byte array

本问题已经有最佳答案,请猛点这里访问。

Possible Duplicate:
How do you convert Byte Array to Hexadecimal String, and vice versa, in C#?

是否可以以完全相同的方式将字符串的内容转换为字节数组?

例如:我有一个类似以下的字符串:

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

如果我将strbytes传递给函数,是否有函数可以给出以下结果?

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


没有内置的方法,但您可以使用LINQ来实现这一点:

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


1
2
3
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));


1
2
3
4
5
6
7
8
9
10
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
}