Convert string data to byte[]

Posted on 2005-04-08
Last Modified: 2010-04-16

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.



Question by:yamazed
    1 Comment
    LVL 8

    Accepted 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);

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    How your wiki can always stay up-to-date

    Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
    - Increase transparency
    - Onboard new hires faster
    - Access from mobile/offline

    Introduction Hi all and welcome to my first article on Experts Exchange. A while ago, someone asked me if i could do some tutorials on object oriented programming. I decided to do them on C#. Now you may ask me, why's that? Well, one of the re…
    Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
    This video discusses moving either the default database or any database to a new volume.
    Here's a very brief overview of the methods PRTG Network Monitor ( offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…

    760 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    14 Experts available now in Live!

    Get 1:1 Help Now