如何将 UTF-8 byte[] 转换为字符串
如何将 UTF-8 byte[] 转换为字符串
我有一个从文件中加载的 byte[]
数组,我碰巧知道它包含 UTF-8。
在一些调试代码中,我需要将其转换为字符串。有没有一行代码可以做到这一点?
在底层,它应该只是分配和复制内存,所以即使它没有被实现,也应该是可能的。
admin 更改状态以发布 2023年5月21日
有至少四种不同的方法可以进行此转换。
-
Encoding 的 GetString
,但如果这些字节具有非 ASCII 字符,则无法获得原始字节。 -
BitConverter.ToString
输出是一个以“-”分隔的字符串,但没有 .NET 内置的方法将字符串转换回字节数组。 -
Convert.ToBase64String
您可以使用Convert.FromBase64String
轻松将输出字符串转换回字节数组。
注意:输出字符串可能包含“+”、“/”和“=”。如果要在 URL 中使用字符串,则需要显式地对其进行编码。 -
HttpServerUtility.UrlTokenEncode
您可以使用HttpServerUtility.UrlTokenDecode
轻松将输出字符串转换回字节数组。输出字符串已经适用于 URL!缺点是,如果您的项目不是 Web 项目,则需要使用System.Web
程序集。
一个完整的示例:
byte[] bytes = { 130, 200, 234, 23 }; // A byte array contains non-ASCII (or non-readable) characters string s1 = Encoding.UTF8.GetString(bytes); // ��� byte[] decBytes1 = Encoding.UTF8.GetBytes(s1); // decBytes1.Length == 10 !! // decBytes1 not same as bytes // Using UTF-8 or other Encoding object will get similar results string s2 = BitConverter.ToString(bytes); // 82-C8-EA-17 String[] tempAry = s2.Split('-'); byte[] decBytes2 = new byte[tempAry.Length]; for (int i = 0; i < tempAry.Length; i++) decBytes2[i] = Convert.ToByte(tempAry[i], 16); // decBytes2 same as bytes string s3 = Convert.ToBase64String(bytes); // gsjqFw== byte[] decByte3 = Convert.FromBase64String(s3); // decByte3 same as bytes string s4 = HttpServerUtility.UrlTokenEncode(bytes); // gsjqFw2 byte[] decBytes4 = HttpServerUtility.UrlTokenDecode(s4); // decBytes4 same as bytes