| 网站首页 | 文章中心 | 电子书下载 | 矢量图库 | 视频教程 | 素材下载 | 程序代码下载 | JS代码 | 论坛 | 
常用软件类:
|杀毒安全 |联络聊天 |网络软件 |多媒体类 |系统工具 |图形图像 |系统工具 |应用软件 |行业软件
开发设计类:
|动画制作 |图像处理 |3D设计 |操作系统 |站长学院 |网络相关 |WEB设计 |数据库类 |程序开发
asp.net把utf-8编码转换为gb2312编码
作者:未知    文章来源:网络    点击数:    更新时间:2006-7-1
 

最近在做的系统中,碰到了一个问题,交易系统采用的utf-8编码,而一些支持系统使用的是gb2312编码。

不同编码的页面、脚本之间互相引用,就会产生乱码的问题,解决方法就是统一成一种编码。
asp.net 中,如果要修改输出页面的编码,可以通过修改web.config中以下配置信息


<globalization requestencoding="utf-8" responseencoding="utf-8" />
以上只是修改整体的默认编码,如果只有某个页的编码需要修改,asp.net 中则可以简单的使用下面代码:


注:加到page_load()事件下面就可以了
encoding gb2312 = encoding.getencoding("gb2312");
response.contentencoding = gb2312;
在非asp.net 应用中,可能你读到的数据是utf-8编码,但是你要转换为gb2312编码,则可以参考以下代码:

string utfinfo = "document.write(\"alert('你好么??');\");";
string gb2312info = string.empty;

encoding utf8 = encoding.utf8;
encoding gb2312 = encoding.getencoding("gb2312");

/ convert the string into a byte[].
byte[] unicodebytes = utf8.getbytes(utfinfo);
/ perform the conversion from one encoding to the other.
byte[] asciibytes = encoding.convert(utf8, gb2312, unicodebytes);
           
/ convert the new byte[] into a char[] and then into a string.
/ this is a slightly different approach to converting to illustrate
/ the use of getcharcount/getchars.
char[] asciichars = new char[gb2312.getcharcount(asciibytes, 0, asciibytes.length)];
gb2312.getchars(asciibytes, 0, asciibytes.length, asciichars, 0);
gb2312info = new string(asciichars);

当然,其他各种编码之间的转换,跟上述代码也类似的,就不描述了。


相关文章