编码与解码

下面的示例演示了如何使用 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
 
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值