convert string to byte array [duplicate]
Possible Duplicate:
How do you convert Byte Array to Hexadecimal String, and vice versa, in C#?
Is it possbile to convert the content of a string in exactly the same way to a byte array?
For example: I have a string like:
string strBytes="0xab, 0xcd, 0xef, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x01, 0x23, 0x45, 0x67, 0x89";
Is there any function which can give me the following result if i pass strBytes to it.
Byte[] convertedbytes ={0xab开发者_高级运维, 0xcd, 0xef, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x01, 0x23, 0x45, 0x67, 0x89};
There's no built-in way, but you can use LINQ to do that:
byte[] convertedBytes = strBytes.Split(new[] { ", " }, StringSplitOptions.None)
.Select(str => Convert.ToByte(str, 16))
.ToArray();
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
}
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));
精彩评论