Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String to byte[] and vice versa? [duplicate]

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.

like image 487
Edward83 Avatar asked Nov 30 '10 21:11

Edward83


3 Answers

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);
like image 53
cdhowie Avatar answered Nov 12 '22 00:11

cdhowie


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.

like image 39
Will Vousden Avatar answered Nov 12 '22 00:11

Will Vousden


Use the Encoding class.

like image 3
Oded Avatar answered Nov 12 '22 00:11

Oded