开发者

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

开发者 https://www.devze.com 2023-01-27 22:01 出处:网络
This question already has answers here: 开发者_运维百科 Closed 12 years ago. Possible Duplicate: .NET String to byte Array C#
This question already has answers here: 开发者_运维百科 Closed 12 years ago.

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.


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);


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.


Use the Encoding class.


How do I get a consistent byte representation of strings in C# without manually specifying an encoding?

0

精彩评论

暂无评论...
验证码 换一张
取 消