In the system I was working on recently, I encountered a problem. The trading system uses UTF-8 encoding, while some supporting systems use GB2312 encoding.
If pages and scripts with different encodings reference each other, garbled characters will occur. The solution is to unify them into one encoding.
In asp.net, if you want to modify the encoding of the output page, you can modify the following configuration information in web.config
<globalization requestEncoding="utf-8" responseEncoding="utf-8" />
The above is just to modify the overall default encoding. If only the encoding of a certain page needs to be modified, you can simply use the following code in ASP.net:
Note: Just add it below the Page_Load() event.
Encoding gb2312 = Encoding.GetEncoding("gb2312");
Response.ContentEncoding = gb2312;
In non-ASP.net applications, the data you may read is UTF-8 encoded, but if you want to convert it to GB2312 encoding, you can refer to the following code:
string utfinfo = "document.write("alert('How are you??');");";
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);
Of course, the conversion between various other encodings is similar to the above code and will not be described.