将字符串转换为byte[]

本文关键字:byte 字符串 转换 | 更新日期: 2023-09-27 17:50:13

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

将字符串转换为byte[]

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

注意。net字符串被编码为Unicode (UTF-16):

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

您可以使用LINQ:

var input     = "myValue";
var byteInput = input.ToCharArray ().Select ( character => ( byte ) character ).ToArray ();
Assert.AreEqual ( input, new string ( byteInput.Select ( character => ( char ) character ).ToArray () ) );

如果您想要编码,则在编码之前或之后添加编码