最近在做的系統中,碰到了一個問題,交易系統采用的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);
當然,其他各種編碼之間的轉換,跟上述代碼也類似的,就不描述了。
新聞熱點
疑難解答
圖片精選