Convert string data to byte[]


I have the following binary data:

StringData = 800006000000;

I would like to parse it as follow:

byte[] bytes = new byte[6];
bytes[0] = 0x80;
bytes[1] = 0x00;
bytes[2] = 0x06;
bytes[3] = 0x00;
bytes[4] = 0x00;
bytes[5] = 0x00;

How can I parse the string StringData  to the equivalent byte array above?

I tried the following:
byte[] bytes =  Encoding.ASCII.GetBytes(StringData);

but it gave me back garbage data.

This bytes[0] = 0x80; is equivalent to bytes[0] = 128; while with the above code I was getting back a set of 48 and 54...

Any help would be appreciated.



Who is Participating?
AaronReamsConnect With a Mentor Commented:
Your problem is when you do ASCII.GetBytes you are getting the ascii value of each individual character.  You actually want the hexadecimal representation.

            string StringData = "800006000000";
            byte[] bytes =  new byte[StringData.Length/2];
            for(int i=0; i<StringData.Length/2; i++)
                bytes[i]= (byte)Convert.ToSByte(StringData.Substring(i*2,1)+StringData.Substring(i*2+1,1),16);
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.