• Unicode和汉字编码小知识


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

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

    -C#
    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;
        }
    }
  • 相关阅读:
    ABP 使用ElasticSearch、Kibana、Docker 进行日志收集
    Team Foundation Server 2005单服务器版本部署指南
    Echarts 3D地图下钻
    响应式图像与优化
    字节一面:go的协程相比线程,轻量在哪?
    Gopher必读:HttpClient的两个坑位
    客户端禁用Keepalive, 服务端开启Keepalive,会怎么样?
    自古以来,JSON序列化就是兵家必争之地
    Go的优雅终止姿势
    推荐一个好用的浏览器笔记工具
  • 原文地址:https://www.cnblogs.com/codeloves/p/2975812.html
Copyright © 2020-2023  润新知