简体   繁体   中英

convert string to byte[]

如何在C#中将字符串转换为byte []?

请注意,.NET字符串编码为Unicode (UTF-16):

byte[] bytes = Encoding.Unicode.GetBytes("a string");

使用byte[] data = Encoding.UTF8.GetBytes(myString);

You can use LINQ:

var input     = "myValue";
var byteInput = input.ToCharArray ().Select ( character => ( byte ) character ).ToArray ();

Assert.AreEqual ( input, new string ( byteInput.Select ( character => ( char ) character ).ToArray () ) );

And add the encoding before or after if encoding is something you want to do.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM