C#如何改变字符串编码
public string UTF8ToGB2312(string str)
{
try
{
Encoding utf8 = Encoding.GetEncoding(65001);
Encoding gb2312 = Encoding.GetEncoding("gb2312");//Encoding.Default ,936
byte[] temp = utf8.GetBytes(str);
byte[] temp1 = Encoding.Convert(utf8, gb2312, temp);
string result = gb2312.GetString(temp1);
return result;
}
catch (Exception ex)//(UnsupportedEncodingException ex)
{
MessageBox.Show(ex.ToString());
return null;
}
}
public string GB2312ToUTF8(string str)
{
try
{
Encoding uft8 = Encoding.GetEncoding(65001);
Encoding gb2312 = Encoding.GetEncoding("gb2312");
byte[] temp = gb2312.GetBytes(str);
MessageBox.Show("gb2312的编码的字节个数:" + temp.Length);
for (int i = 0; i < temp.Length; i++)
{
MessageBox.Show(Convert.ToUInt16(temp[i]).ToString());
}
byte[] temp1 = Encoding.Convert(gb2312, uft8, temp);
MessageBox.Show("uft8的编码的字节个数:" + temp1.Length);
for (int i = 0; i < temp1.Length; i++)
{
MessageBox.Show(Convert.ToUInt16(temp1[i]).ToString());
}
string result = uft8.GetString(temp1);
return result;
}
catch (Exception ex)//(UnsupportedEncodingException ex)
{
MessageBox.Show(ex.ToString());
return null;
}
}
代码说明:
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格式。
最新文章
- Win8 Metro动态加载内容框架
- z-index
- jQuery.is() 函数
- MVC学习网站
- 软件工程结组开发软件特色——NABC模型
- yum报错: Error: Cannot retrieve metalink for repository: epel. Please verify its path and try again
- ps小技巧
- cocos2dx新建android项目lib拷贝、访问权限等问题集
- QT设置窗口屏幕居中
- poi大数据将excel2007导入数据库
- Oracle实战笔记(第六天)之PL/SQL基础
- *hdu 5536(字典树的运用)
- 浅析ajax原理与用法
- HTML5-MathML-基础篇
- underscore.js学习笔记
- 算法笔记--极大极小搜索及alpha-beta剪枝
- Vue-父子组件传值
- JavaScript 无刷新修改浏览器URL地址栏
- 获取连接的用户ip
- C++ 关于 CMFCPropertyGridCtrl 的使用方法 之一 (原创)
热门文章
- Hibernate 中 get()和load()的区别
- md5 加解密
- OpenCV 2.4.9 学习笔记(2)—— OpenCV内存自动管理
- 让JavaScript像C#一样支持Region
- C++虚函数表解析(基础篇)
- 飞扬的小鸟(NOIP2014)(丧病DP题)
- Scenes in Cocos2D
- 原 android重启应用(应用重新启动自身)
- 判断dataset是否被修改—DataSet.HasChanges 方法
- Python的功能模块[1] ->; struct ->; struct 在网络编程中的使用