.net unicode汉字互相转换

【两种方法】.net unicode汉字互相转换

=========================================


 


//汉字转Unicode编码(ASCII)

private string StringToUnicode(string srcText)

        {

            string dst = "";

            char[] src = srcText.ToCharArray();

            for (int i = 0; i < src.Length; i++)

            {

                byte[] bytes = Encoding.Unicode.GetBytes(src[i].ToString());

                string str = @"\u" + bytes[1].ToString("X2") + bytes[0].ToString("X2");

                dst += str;

            }

            return dst;

        }

 

//TO汉字 srcText为去除\u之后的4位字符


using System.Globalization;



private string ToCN(string srcText)

        {

            string str = srcText;

            byte[] bytes = new byte[2];

            bytes[1] = byte.Parse(int.Parse(str.Substring(0, 2), NumberStyles.HexNumber).ToString());

            bytes[0] = byte.Parse(int.Parse(str.Substring(2), NumberStyles.HexNumber).ToString());

            return Encoding.Unicode.GetString(bytes);

        }


 

================================================================
public static string ConvertToGB(string unicodeString)  
     {  
         string[] strArray = unicodeString.Split(new string[] { @"u" }, StringSplitOptions.None);  
         string result = string.Empty;  
         for (int i = 0; i < strArray.Length; i++)  
         {  
             if (strArray[i].Trim() == "" || strArray[i].Length < 2 || strArray.Length <= 1)  
             {  
                 result += i == 0 ? strArray[i] : @"u" + strArray[i]; continue;  
             }   
             for (int j = strArray[i].Length > 4 ? 4 : strArray[i].Length; j >= 2; j--)  
             {  
                 try  
                 {  
                     result += char.ConvertFromUtf32(Convert.ToInt32(strArray[i].Substring(0, j), 16)) + strArray[i].Substring(j);  
                     break;  
                 }  
                 catch  
                 {  
                     continue;  
                 }  
             }  
         } return result;  
     }  
  
     public static string ConvertToUnicode(string strGB)  
     {  
         char[] chs = strGB.ToCharArray(); string result = string.Empty; foreach (char c in chs)  
         {  
             result += @"u" + char.ConvertToUtf32(c.ToString(), 0).ToString("x");  
         }  
         return result;  
     }

 

转载于:https://www.cnblogs.com/oshoh/p/8520583.html

你可能感兴趣的:(.net unicode汉字互相转换)