C#中的字符串及其编码转换
(转自:http://blog.sina.com.cn/s/blog_498eab7d0100et7j.html)
根据查找的System.Text.Encoding类的属性,方法写了如下的转换程序:
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 } 18 public string GB2312ToUTF8(string str) 19 ...{ 20 try 21 ...{ 22 Encoding uft8 = Encoding.GetEncoding(65001); 23 Encoding gb2312 = Encoding.GetEncoding("gb2312"); 24 byte[] temp = gb2312.GetBytes(str); 25 MessageBox.Show("gb2312的编码的字节个数:" + temp.Length); 26 for (int i = 0; i < temp.Length; i++) 27 ...{ 28 MessageBox.Show(Convert.ToUInt16(temp[i]).ToString()); 29 } 30 byte[] temp1 = Encoding.Convert(gb2312, uft8, temp); 31 MessageBox.Show("uft8的编码的字节个数:" + temp1.Length); 32 for (int i = 0; i < temp1.Length; i++) 33 ...{ 34 MessageBox.Show(Convert.ToUInt16(temp1[i]).ToString()); 35 } 36 string result = uft8.GetString(temp1); 37 return result; 38 } 39 catch (Exception ex)//(UnsupportedEncodingException ex) 40 ...{ 41 MessageBox.Show(ex.ToString()); 42 return null; 43 } 44 }
主要使用的就是获取编码方式的类对象,
Encoding utf8 = Encoding.GetEncoding(65001);//使用code page
Encoding gb2312 = Encoding.GetEncoding("gb2312");//通过bodyname
获取字符编码字节序列:byte[] temp=utf8.GetBytes(str);
编码方式转换:byte[] temp1=Encoding.Convert(utf8, gb2312, temp);
获取编码的字符串:string str1=gb2312.GetString(temp1);
这样即完成了字符编码的转换。
Encoding.Default在 简体中文os中一般是gb2312格式
网上流传的第二种方法:
在使用MySql时会遇到中文乱码的问题就此写下面两个函数
*
在写入数据库和从数据库读出时将编码改变
*
author:alice
*
date
:2006/1/25
*/
//写入数据库时进行转换
1 public string GB2312_ISO8859(string write) 2 { 3 //声明字符集 4 System.Text.Encoding iso8859, gb2312; 5 //iso8859 6 iso8859 = System.Text.Encoding.GetEncoding("iso8859-1"); 7 //国标2312 8 gb2312 = System.Text.Encoding.GetEncoding("gb2312"); 9 byte[] gb; 10 gb = gb2312.GetBytes(write); 11 //返回转换后的字符 12 return iso8859.GetString(gb); 13 } 14 15 //读出时进行转换 16 public string ISO8859_GB2312(string read) 17 { 18 //声明字符集 19 System.Text.Encoding iso8859,gb2312; 20 //iso8859 21 iso8859 = System.Text.Encoding.GetEncoding("iso8859-1"); 22 //国标2312 23 gb2312 = System.Text.Encoding.GetEncoding("gb2312"); 24 byte[] iso; 25 iso = iso8859.GetBytes(read); 26 //返回转换后的字符 27 return gb2312.GetString(iso); 28 }