C# 计算输入汉字的GBK编码,十六进制数输出

C# 计算输入汉字的GBK编码,十六进制数输出

代码语言:javascript
复制
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace getCode
{
    class Program
    { 
&nbsp;       /// <summary>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; /// 计算输入汉字对应的GBK编码主函数入口
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; /// </summary>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; /// <param name="args">< /param>&nbsp;static void Main(string[] args)
        {
            try
            {
                while (true)
                {
                    char cWord = (char)Console.Read();//读入一个汉字
                    byte[] bGb2312 = Encoding.GetEncoding("gbk").GetBytes(new Char[] { cWord });//<span id="mt1" class="sentence" data-guid="21b4c66a1cae34f4812147989864f337" data-source="Returns the encoding associated with the specified code page name.">返回gbk的编码</span>对象的字节数组,包含对cWord进行编码的结果。
                    int n = (int)bGb2312[0] << 8;//第一个字节左移八位
                    n += (int)bGb2312[1];
                    Console.WriteLine("汉字{0}的gbk编码为:{1,4:x4}" ,cWord, n);//输出汉字对应是十六进制GBK编码
                    Console.ReadKey();
                }
            }
            catch
            {
               Console.WriteLine("输入错误!请输入汉字字符!");
          }
        }
    }
}
 </pre>