Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String to byte array [duplicate]

Tags:

c#

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

like image 441
Manu Avatar asked Oct 24 '11 16:10

Manu


2 Answers

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);
like image 178
Dan Byström Avatar answered Sep 20 '22 19:09

Dan Byström


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"

like image 33
abelenky Avatar answered Sep 18 '22 19:09

abelenky