String to byte[] and vice versa?

12,187

Solution 1

If you want to use UTF-8 encoding:

// string to byte[]
byte[] bytes = Encoding.UTF8.GetBytes(someString);

// byte[] to string
string anotherString = Encoding.UTF8.GetString(bytes);

Solution 2

Before you march off and use one of the examples someone's already given you should be aware that there is, in general, no unique mapping between a string and a sequence of bytes. How the string is mapped to binary (and vice versa) is determined by the encoding that you use. Joel Spolsky wrote an awesome article on this subject.

When decoding binary to get a string, you need to use the same encoding as was used to produce the binary in the first place, otherwise you'll run into problems.

Solution 3

Use the Encoding class.

Share:
12,187
Edward83
Author by

Edward83

Updated on July 27, 2022

Comments

  • Edward83
    Edward83 almost 2 years

    Possible Duplicate:
    .NET String to byte Array C#

    How do I convert String to byte[] array and vice versa? I need strings to be stored in some binary storage. Please show example in both directions. And one more thing: each string maybe bigger than 90Kb.

  • dbJones
    dbJones about 7 years
    1+ for link to docs