C# 将 byte[] 数组转换为字符串
要将 C# 中的 'byte[]' 数据转化为字符串,可以使用 'Encoding' 类中的 'GetString' 方法。以下是示例代码:
byte[] bytes = new byte[] { 72, 101, 108, 108, 111 }; // 'Hello' 的 ASCII 码值
string str = Encoding.ASCII.GetString(bytes);
Console.WriteLine(str); // 输出 'Hello'
在上面的示例中,我们使用了 ASCII 编码将字节数组转换为字符串。如果 'byte[]' 数组中的数据采用了其他编码方式,例如 UTF-8 或 UTF-16,可以使用相应的编码方式进行解码。例如:
byte[] bytes = new byte[] { 0xE4, 0xBD, 0xA0, 0xE5, 0xA5, 0xBD }; // '你好' 的 UTF-8 编码
string str = Encoding.UTF8.GetString(bytes);
Console.WriteLine(str); // 输出 '你好'
需要注意的是,'byte[]' 数组转换为字符串时,需要指定正确的编码方式,否则可能会出现乱码等问题。
原文地址: https://www.cveoy.top/t/topic/nPFl 著作权归作者所有。请勿转载和采集!