下面的示例演示了如何使用 UTF8Encoding 对 Unicode 字符串进行编码,并将它们存储在字节数组中。请注意,将 encodedBytes 解码回字符串时不会丢失数据。
using System; using System.Text; class UTF8EncodingExample { public static void Main() { // Create a UTF-8 encoding.
//生成utf8对象
UTF8Encoding utf8 = new UTF8Encoding(); // A Unicode string with two characters outside an 8-bit code range. // uf8字符串
String unicodeString = "This unicode string contains two characters " + "with codes outside an 8-bit code range, " + "Pi (\u03a0) and Sigma (\u03a3)."; Console.WriteLine("Original string:"); Console.WriteLine(unicodeString); // Encode the string.
//通过utf8.getbytes方法对字符串进行utf8编码
Byte[] encodedBytes = utf8.GetBytes(unicodeString); Console.WriteLine(); Console.WriteLine("Encoded bytes:");
//通过foreach循环把byte数组中每个元素显示出来
foreach (Byte b in encodedBytes) // b为数组元素 encodedbytes为数组
{ Console.Write("[{0}]", b); } Console.WriteLine(); // Decode bytes back to string. // Notice Pi and Sigma characters are still present.
//用utf8.getstring把编码的utf8解码出来,解码与编码是反向操作
String decodedString = utf8.GetString(encodedBytes); Console.WriteLine(); Console.WriteLine("Decoded bytes:"); Console.WriteLine(decodedString); } }
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/9240380/viewspace-709858/ ,如需转载,请注明出处,否则将追究法律责任。