zoukankan      html  css  js  c++  java
  • Unicode和汉字编码小知识

    Unicode和汉字编码小知识
      将汉字进行UNICODE编码,如:“王”编码后就成了“王”,UNICODE字符以u开始,后面有4个数字或者字母,所有字符都是16进制的数字,每两位表示的256以内的一个数字。而一个汉字是由两个字符组成,于是就很容易理解了,“738b”是两个字符,分别是“73”“8b”。但是在将 UNICODE字符编码的内容转换为汉字的时候,
    字符是从后面向前处理的,所以,需要把字符按照顺序“8b”“73”进行组合得到汉字

      下面是C#汉字Unicode编码相互转换代码。

    using System;
    using System.Text;
    using System.Text.RegularExpressions;
    using System.Globalization;
    public class GB2312UnicodeConverter
    {
        /// <summary>
        /// 汉字转换为Unicode编码
        /// </summary>
        /// <param name="str">要编码的汉字字符串</param>
        /// <returns>Unicode编码的的字符串</returns>
        public static string ToUnicode(string str)
        {
            byte[] bts = Encoding.Unicode.GetBytes(str);
            string r = "";
            for (int i = 0; i < bts.Length; i += 2) r += "\u" + bts[i + 1].ToString("x").PadLeft(2, '0') + bts[i].ToString("x").PadLeft(2, '0');
            return r;
        }
        /// <summary>
        /// 将Unicode编码转换为汉字字符串
        /// </summary>
        /// <param name="str">Unicode编码字符串</param>
        /// <returns>汉字字符串</returns>
        public static string ToGB2312(string str)
        {
            string r = "";
            MatchCollection mc = Regex.Matches(str, @"\u([w]{2})([w]{2})", RegexOptions.Compiled | RegexOptions.IgnoreCase);
            byte[] bts = new byte[2];
            foreach(Match m in mc )
            {
                bts[0] = (byte)int.Parse(m.Groups[2].Value, NumberStyles.HexNumber);
                bts[1] = (byte)int.Parse(m.Groups[1].Value, NumberStyles.HexNumber);
                r += Encoding.Unicode.GetString(bts);
            }
            return r;
        }
    }

     
     
     
     
    阅读(
  • 相关阅读:
    PKG_CONFIG_PATH 、LD_LIBRARY_PATH、PATH三个的作用
    klocwork报错:Error occurred during build: C/C+ defects detection stage failed. Program exited with 139
    修改默认内核启动以及删除Linux多余的内核
    【笔记】ubuntu内核升级到4.19后,docker服务无法启动
    TypeError: unhashable type: 'collections.OrderedDict'
    jquery 如何给新生成的元素绑定 hover事件?
    css中判断IE版本的语句
    (转)JS获取当前对象大小以及屏幕分辨率等
    (转)ie浏览器判断
    (转)javascript中的this
  • 原文地址:https://www.cnblogs.com/zhangxiaolei521/p/5390997.html
Copyright © 2011-2022 走看看