C# byte数组转string

当将byte数组转换为string时,需要确定byte数组中的数据是如何编码的。下面是几种示例:

1.使用默认编码: 

byte[] byteArray = { 72, 101, 108, 108, 111 }; // "Hello" 的 ASCII 编码
string str = Encoding.Default.GetString(byteArray);
Console.WriteLine(str); // 输出: Hello

2.使用UTF-8编码:

byte[] byteArray = { 228, 184, 150, 231, 149, 140 }; // "你好" 的 UTF-8 编码
string str = Encoding.UTF8.GetString(byteArray);
Console.WriteLine(str); // 输出: 你好

3.使用UTF-16编码:

byte[] byteArray = { 255, 254, 72, 0, 101, 0, 108, 0, 108, 0, 111, 0 }; // "Hello" 的 UTF-16 编码(Little-Endian)
string str = Encoding.Unicode.GetString(byteArray);
Console.WriteLine(str); // 输出: Hello

4.使用自定义编码:

byte[] byteArray = { 197, 169, 197, 176, 197, 178 }; // 自定义编码的示例数据
Encoding encoding = Encoding.GetEncoding("ISO-8859-1"); // 使用 ISO-8859-1 编码
string str = encoding.GetString(byteArray);
Console.WriteLine(str); // 输出: éèû

猜你喜欢

转载自blog.csdn.net/weixin_53482897/article/details/131507438
今日推荐