Tuesday, November 24, 2009

How to convert a string to a byte array and vice versa

Use one of the System.Text.Encoding-derived classes that supports all Unicode character values. Most commonly used one is UTF8Encoding class that encodes Unicode characters using the UTF-8 encoding.

public byte[] StringToByteArray(String text)
    System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
    return encoding.GetBytes(text);

The same can be done using the Encoding.UTF8 property:

byte[] bytes = System.Text.Encoding.UTF8.GetBytes(text);

Do not use ASCIIEncoding, in this case you will lose all the characters that are not defined by ASCII (A-Z, a-z, 0-9 and some punctuation marks).

Note that you will get different results depending on the encoding class you use.

To convert a byte array back to a string, use the GetString method of the same encoding class:

String text = System.Text.Encoding.UTF8.GetString(bytes);

No comments:

Post a Comment