0

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};
Community
  • 1
  • 1
logeeks
  • 4,849
  • 15
  • 62
  • 93
  • This _question_ contains a function to do exactly that. http://stackoverflow.com/q/6889400/60761 – H H Jul 31 '11 at 18:31

3 Answers3

1

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();
Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479
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
}
Jalal Said
  • 15,906
  • 7
  • 45
  • 68
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));
sll
  • 61,540
  • 22
  • 104
  • 156