把UTF-8編碼轉(zhuǎn)換為GB2312編碼

2010-08-28 10:48:27來源:西部e網(wǎng)作者:

最近在做的廣告系統(tǒng)中,碰到了一個問題,廣告系統(tǒng)采用的UTF-8編碼,而一些使用這套廣告系統(tǒng)的頻道頁面使用的是GB2312編碼。當(dāng)然也有使用UTF-8編碼的頻道使用這套廣告系統(tǒng)。

頻道頁面是通過嵌入類似如下的代碼方式,來調(diào)用廣告的。具體那個時間顯示那個廣告,或者那些廣告組合是廣告系統(tǒng)自己處理的。

<script type="text/javascript">
<!--
csdn_AD_Position_GroupID = "{f05ff3bf-246b-4d71-a101-b5d4ee3f6cd3}";
csdn_AD_Page_Url = document.location;
//-->
</script>
<script type="text/javascript" src="http://xxx/AD/Show_JavaScript_AD.js" >
</script>

不同編碼的頁面、腳本之間互相引用,就會產(chǎn)生亂碼的問題,解決方法就是統(tǒng)一成一種編碼。
asp.net 中,如果要修改輸出頁面的編碼,可以通過修改web.config中以下配置信息


<globalization requestEncoding="utf-8" responseEncoding="utf-8" />
以上只是修改整體的默認(rèn)編碼,如果只有某個頁的編碼需要修改,ASP.net 中則可以簡單的使用下面代碼:

Encoding gb2312 = Encoding.GetEncoding("gb2312");
Response.ContentEncoding = gb2312;
在非ASP.net 應(yīng)用中,可能你讀到的數(shù)據(jù)是UTF-8編碼,但是你要轉(zhuǎn)換為GB2312編碼,則可以參考以下代碼:

string utfinfo = "document.write(\"alert('aa你好么??');\");";
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);

當(dāng)然,其他各種編碼之間的轉(zhuǎn)換,跟上述代碼也類似的,就不描述了。

關(guān)鍵詞:UTF-8GB2312編碼

贊助商鏈接: