Conversion between UNICODE and Chinese character encoding
To avoid Chinese garbled Characters During data transmission in the browser, We can encode the content in URL or UNICODE. UNICODE encoding of Chinese characters, such as "King", which becomes "/u738b". The UNICODE character starts with "/u" and is followed by four numbers or letters, all characters are hexadecimal numbers. Each two character represents a number less than 256. A Chinese character is composed of two characters, so it is easy to understand that "738b" is two characters, namely "73" and "8b ". However, when converting the UNICODE character encoding content to Chinese characters, the characters are processed forward from the back. Therefore, you need to combine the characters in the order of "8b" and "73" to get Chinese characters. The following is the specific conversion code.
/// <Summary>
/// Convert Chinese characters to Unicode
/// </Summary>
/// <Param name = "text"> string to be converted </param>
/// <Returns> </returns>
Public static string GBToUnicode (string text)
{
Byte [] bytes = System. Text. Encoding. Unicode. GetBytes (text );
String lowCode = "", temp = "";
For (int I = 0; I <bytes. Length; I ++)
{
If (I % 2 = 0)
{
Temp = System. Convert. ToString (bytes [I], 16); // extracts element 4 encoded content (two hexadecimal digits)
If (temp. Length <2) temp = "0" + temp;
}
Else
{
String mytemp = Convert. ToString (bytes [I], 16 );
If (mytemp. length <2) mytemp = "0" + mytemp; lowCode = lowCode + @ "/u" + mytemp + temp; // extracts element 4 encoded content (two hexadecimal values)
}
}
Return lowCode;
}
/// <Summary>
/// Convert Unicode to Chinese Characters
/// </Summary>
/// <Param name = "name"> string to be converted </param>
/// <Returns> </returns>
Public string UnicodeToGB (string text)
{
MatchCollection mc = Regex. Matches (text, "([// w] +) | (// u ([// w] {4 }))");
If (mc! = Null & mc. Count> 0)
{
StringBuilder sb = new StringBuilder ();
Foreach (Match m2 in mc)
{
String v = m2.Value;
If (v. StartsWith ("http://www.cnblogs.com/xczt/admin/file://u "))
{
String word = v. Substring (2 );
Byte [] codes = new byte [2];
Int code = Convert. ToInt32 (word. Substring (0, 2), 16 );
Int code2 = Convert. ToInt32 (word. Substring (2), 16 );
Codes [0] = (byte) code2;
Codes [1] = (byte) code;
Sb. Append (Encoding. Unicode. GetString (codes ));
}
Else
{
Sb. Append (v );
}
}
Return sb. ToString ();
}
Else
{
Return text;
}
}
Ps: This is a good knowledge.