9

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

I've an string like this: "021500010000146DE6D800000000000000003801030E9738"

What I need is the following byte array: 02 15 00 01 00 00 14 6D E6 D8 00 00 00 00 00 00 00 00 38 01 03 0E 97 38 (each pair of number is the hexadecimal value in the respective byte).

Any idea about how can I make this conversion?? Thanks!!

6
  • Did you to write to do something ? Commented Oct 24, 2011 at 16:32
  • 1
    The “possible duplicate” is a completely different question. He's not asking how to encode the string into a byte[] using some encoding. The string here contains hexadecimal values that should be converted to byte[]. Commented Oct 24, 2011 at 16:36
  • I don't see how these questions are exact duplicates. Commented Oct 24, 2011 at 16:39
  • You pretty much want the second example on this page: msdn.microsoft.com/en-us/library/bb311038.aspx. The "meat" of it is Convert.ToInt32(hex, 16) (the second parameter specifies to convert from Base-16, which is Hex). I found this with Google: "C# parse hex" Commented Oct 24, 2011 at 16:46
  • I've also seen the "duplicate" thread, and I really think this is completely different. Commented Oct 24, 2011 at 16:56

3 Answers 3

5
var arr = new byte[s.Length/2];
for ( var i = 0 ; i<arr.Length ; i++ )
    arr[i] = (byte)Convert.ToInt32(s.SubString(i*2,2), 16);
Sign up to request clarification or add additional context in comments.

2 Comments

This code is really working well. But only a detail, right code is "s.Substring". Thanks to all.
Can use Convert.ToByte instead of ToInt32.
1

You pretty much want the second example on this page.
The important part is:

Convert.ToInt32(hex, 16);

The first parameter is a 2-character string, specifying a hex-value (e.g. "DE").
The second parameter specifies to convert from Base-16, which is Hex.

Splitting the string up into two-character segments isn't shown in the example, but is needed for your problem. I trust its simple enough for you to handle.

I found this with Google: "C# parse hex"

Comments

1
    string str = "021500010000146DE6D800000000000000003801030E9738";
    List<byte> myBytes = new List<byte>();

    try
    {
        while (!string.IsNullOrEmpty(str))
        {
            myBytes.Add(Convert.ToByte(str.Substring(0, 2), 16));
            str = str.Substring(2);
        }
    }
    catch (FormatException fe)
    {
        //handle error
    }
    for(int i = 0; i < myBytes.Count; i++)
    {
        Response.Write(myBytes[i].ToString() + "<br/>");
    }

2 Comments

Convert.ToByte on an int? I mean, premature optimization is bad and all, but when the simplest approach is also faster...
@BenVoigt Ah, I found that right function to do in one convert. Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.