zoukankan      html  css  js  c++  java
  • 汉字与unicode码相互转化

     /// <summary>
            /// 将汉字转换为Unicode
            /// </summary>
            /// <param name="strGB">要转换的字符串</param>
            /// <returns></returns>
            public static string GBToUnicode(string strGB)
            {
                byte[] bytes = System.Text.Encoding.Unicode.GetBytes(strGB);
                string lowCode = "", tmpChar = "";
    
                for (int i = 0; i < bytes.Length; i++)
                {
                    if (i % 2 == 0)
                    {
                        tmpChar = System.Convert.ToString(bytes[i], 16);//取出元素4编码内容(两位16进制)
                        if (tmpChar.Length < 2) 
                            tmpChar = "0" + tmpChar;
                    }
                    else
                    {
                        string mytemp = Convert.ToString(bytes[i], 16);
                        if (mytemp.Length < 2) 
                            mytemp = "0" + mytemp; 
                        lowCode = lowCode + @"\u" + mytemp + tmpChar;//取出元素4编码内容(两位16进制)
                    }
                }
                return lowCode;
            }
    
            /// <summary>
            /// 将Unicode转换为汉字
            /// </summary>
            /// <param name="name">要转换的字符串</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;
                        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));
                    }
                    return sb.ToString();
                }
                else
                {
                    return text;
                }
            }
  • 相关阅读:
    网络基础知识
    mysql安装
    docker打包镜像
    python的基础
    python静态属性的理解
    python中的静态方法和类方法
    python类的两种创建方式
    python的继承
    python中time和datetime模块
    python之模块
  • 原文地址:https://www.cnblogs.com/BlueBeauty/p/2009555.html
Copyright © 2011-2022 走看看