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!!

Community
  • 1
  • 1
Manu
  • 1,130
  • 3
  • 10
  • 26
  • Did you to write to do something ? – Gregory Nozik Oct 24 '11 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[]`. – svick Oct 24 '11 at 16:36
  • I don't see how these questions are exact duplicates. – vcsjones Oct 24 '11 at 16:39
  • You pretty much want the second example on this page: http://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" – abelenky Oct 24 '11 at 16:46
  • I've also seen the "duplicate" thread, and I really think this is completely different. – Manu Oct 24 '11 at 16:56
  • Looks like exact duplicate to me - please comment on how the linked questions are different from what you want: hex string -> byte array (and all samples so far are about the same as potential duplicate ones) – Alexei Levenkov Oct 24 '11 at 17:42

3 Answers3

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);
Dan Byström
  • 9,067
  • 5
  • 38
  • 68
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"

abelenky
  • 63,815
  • 23
  • 109
  • 159
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/>");
    }
Nick Rolando
  • 25,879
  • 13
  • 79
  • 119