Converting String to byte[] and back again

I was working with some networking protocols in C# and I needed a way to convert from a string to byte[] and back again. It took a little time to find the answer, so I thought I would write it down for the next time that I would need it.The secret is in the System.Text namespace.byte[] bAdam = new ASCIIEncoding().GetBytes("Adam");string sAdam = new ASCIIEncoding().GetString(bAdam);byte[] bAdam = Encoding.ASCII.GetBytes("Adam");string sAdam = Encoding.ASCII.GetString(bAdam);

Thanks to James Manning for his suggestion on using the Encoding.ASCII property instead of creating a new ASCIIEnoding instance (as well as other mistakes he pointed out).


4 Responses

  1. I’m guessing on that second line the param should be bAdam 🙂

    Also, rather than creating a new encoding, you can use Encoding.ASCII – ASCII, along with other popular encodings (UTF7, UTF8, Unicode (UTF16), UTF32, etc) are available as static properties so you don’t have to allocate new objects for using them.

    byte[] bAdam = Encoding.ASCII.GetBytes(“Adam”);
    string sAdam = Encoding.ASCII.GetString(bAdam);

  2. You are right. I will make the changes you suggested.

    Thanks for the feedback.

  3. Do you know any code written in C ?

  4. No. I do not know of any code written in C that will do the same thing. I assume that there has to be C code to do this. I just don’t know of any.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: