将字符串转换为字节数组

时间:2011-07-31 18:28:44

标签: c# .net

  

可能重复:
  How do you convert Byte Array to Hexadecimal String, and vice versa, in C#?

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

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

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};

3 个答案:

答案 0 :(得分:1)

没有内置方式,但你可以使用LINQ来做到这一点:

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

答案 1 :(得分: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
}

答案 2 :(得分: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));