风易博客

风萧萧兮易水寒, 壮士一去兮不复还。

« jQuery新手常见问题FAQ奥运圣火国内传递路线时间表! »

C#下字符编码函数

会说话的博客,点我试试:)

GB2312到utf8
 

C#代码
  1. public string GB2312ToUTF8(string str)   
  2. {   
  3.   try  
  4.   {   
  5.     Encoding uft8 = Encoding.GetEncoding(65001);   
  6.     Encoding gb2312 = Encoding.GetEncoding("gb2312");   
  7.     byte[] temp = gb2312.GetBytes(str);   
  8.     MessageBox.Show("gb2312的编码的字节个数:" + temp.Length);   
  9.     for (int i = 0; i < temp.Length; i++)   
  10.     {   
  11.       MessageBox.Show(Convert.ToUInt16(temp[i]).ToString());   
  12.     }       
  13.     byte[] temp1 = Encoding.Convert(gb2312, uft8, temp);   
  14.     MessageBox.Show("uft8的编码的字节个数:" + temp1.Length);   
  15.     for (int i = 0; i < temp1.Length; i++)   
  16.     {   
  17.       MessageBox.Show(Convert.ToUInt16(temp1[i]).ToString());   
  18.     }                  
  19.     string result = uft8.GetString(temp1);   
  20.     return result;   
  21.   }   
  22.   catch  (Exception ex)//(UnsupportedEncodingException ex)   
  23.   {   
  24.     MessageBox.Show(ex.ToString());   
  25.     return null;   
  26.   }   
  27. }  


UTF8转GB2312
 

C#代码
  1. public string UTF8ToGB2312(string str)   
  2. {   
  3.   try  
  4.   {       
  5.     Encoding utf8 = Encoding.GetEncoding(65001);   
  6.     Encoding gb2312 = Encoding.GetEncoding("gb2312");//Encoding.Default ,936   
  7.     byte[] temp = utf8.GetBytes(str);   
  8.     byte[] temp1 = Encoding.Convert(utf8, gb2312, temp);   
  9.     string result = gb2312.GetString(temp1);    
  10.     return result;   
  11.   }   
  12.   catch  (Exception ex)//(UnsupportedEncodingException ex)   
  13.   {   
  14.     MessageBox.Show(ex.ToString());   
  15.     return null;    
  16.   }   
  17. }  

 

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

日历

最新评论及回复

最近发表

Powered By Z-Blog 1.8 Spirit Build 80722 Code detection by Codefense  theme by BokeZhuti

Copyright © 2005 - 2008 风易博客 1982Y.Net.Cn All Rights Reserved.  由Wind88.Net提供优质主机空间
沪ICP备05006417号