编码与解码

来源:互联网 发布:xmodem 软件 编辑:程序博客网 时间:2024/05/16 09:44
下面的示例演示了如何使用UTF8EncodingUnicode 字符串进行编码,并将它们存储在字节数组中。请注意,将encodedBytes解码回字符串时不会丢失数据

usingSystem;usingSystem.Text;classUTF8EncodingExample {publicstaticvoidMain() {// Create a UTF-8 encoding.//生成utf8对象 UTF8Encoding utf8 =newUTF8Encoding();// 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 binencodedBytes)  // 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);    }}转自:http://space.itpub.net/9240380/viewspace-709858
方法:2
编码时可以指定编码的,如 System.Web.HttpUtility.UrlEncode(str,System.Text.Encoding.Unicode); System.Web.HttpUtility.UrlEncode(str,System.Text.Encoding.UTF8); System.Web.HttpUtility.UrlEncode(str,System.Text.Encoding.GetEncoding( "GB2312 "));  解码也可以指定编码的 System.Web.HttpUtility.UrlDecode(str,System.Text.Encoding.Unicode); System.Web.HttpUtility.UrlDecode(str,System.Text.Encoding.UTF8); System.Web.HttpUtility.UrlDecode(str,System.Text.Encoding.GetEncoding( "GB2312 ")); 
出现乱码是编码设置造成的。你可以试试不同的方法。
转自:http://blog.csdn.net/lianchangshuai/article/details/7238855