Learn how to a build a cloud-first strategyRegister Now

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 218
  • Last Modified:

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.



1 Solution
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);

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now