Convert a byte array to a string and string to byte array

Posted on 7/5/2006 @ 11:33 AM in #Vanilla .NET by | Feedback | 6898 views

Okay the actual answer to this is quite complex, because it really depends on the kind of encoding you are using. But assuming that you are using ASCII encoding, (the rest are similar), the code looks like as below --

// String to Byte Array
byte[] monkey = System.Text.Encoding.ASCII.GetBytes("Sahil Malik");

// Byte Array to String

Just a little tidbit that I thought may help some poor soul. Of course feel free to add your knowledge in the comments below.

Sound off but keep it civil:

Older comments..

On 7/5/2006 3:38:04 PM John Wood said ..
One thing worth noting, that i learnt the hard way... if you're ever persisting strings, make sure you use a specific encoding and not Encoding.Default, because when it's deserialized onto a PC with a different default encoding things go pear shaped.

On 7/5/2006 4:55:27 PM Sahil Malik said ..
Yep John - like I said, the actual answer depends on the specific encoding you're using. But well for simplsitic/common scenarios, the above is a good thing to have @ hand. :)

On 7/5/2006 9:28:14 PM Kent Boogaart said ..
The Encoding class is fine when you know all your input bytes / string. However, if you encoding/decoding on the fly based on a stream you're reading, you won't necessarily know all the bytes yet. In that instance, you can use an Encoder or Decoder as given by the Encoding.GetEncoder() and Encoding.GetDecoder() methods.

And another thing - why Base64 encoding wasn't implemented as a specific Encoding is beyond me. Any insight?

And another thing - can you possibly move the refresh button away from the comments box? I'm tipping most people (including me) will click that instead of "Submit Feedback". Thank God the back button got me my content back or I would have had to spew all that crap out again.

On 7/5/2006 10:19:09 PM Sahil Malik said ..
Thanks for your comments Kent.

I am making a list of things I wish to address in my blog engine. To refresh button is one of them. Views is another.

My solution to the refresh button, is to try and do that Ajax based, so when you hit refresh, it refreshes the image, without loosing all your work.

We'll see :) it all boils down to time, but yes I will address that soonish.

On 12/19/2008 5:46:11 AM Malay said ..
Hi Sahil,

Great post.

One question, how to read SPAttachment of listitem and read its content and then copy it in the same ListItems RTF Field. (Multiline Rich text Field)?

Let me know..