19-获取字符的ASCII编码

  • GetEncoding(String) :返回与指定代码页名称关联的编码。

  • String:指的是方法的编码类型

Encoding类下的方法

     GetBytes(Char[]) 在派生类中重写时,将指定字符数组中的所有字符编码为一个字节序列。 

方法概述

 char chr=InPutChinese.Text[0];//获取字符,调用TextBox的text属性,text是一个字符串,这里调用的是字符串中的一个字符,必须有[0];

Encoding.GetEncoding("gb2312").GetBytes(new char[] { chr });//GetBytes()方法,{chr}:数组创建必须有数组大小或数组初始值设定项

不同进制的显示: OutPutTextBox.Text = Convert.ToString(n,2); //二进制,2控制字符串的进制
OutPutTextBox.Text = n.ToString();//十进制显示:

在输入框中输入一个字符,输出框中显示字符

	using System;
	using System.Collections.Generic;
	using System.ComponentModel;
	using System.Data;
	using System.Drawing;
	using System.Linq;
	using System.Text;
	using System.Threading.Tasks;
	using System.Windows.Forms;
	
	namespace _19_获取汉子编码值
	{
	    public partial class Form1 : Form
	    {
	        public Form1()
	        {
	            InitializeComponent();
	        }
	
	        private void label1_Click(object sender, EventArgs e)
	        {
	
	        }
	
	        private void button1_Click(object sender, EventArgs e)
	        {
	            try
	            {
	                char chr=InPutChinese.Text[0];//获取字符,调用TextBox的text属性,text是一个字符串,这里调用的是字符串中的一个字符,必须有[0];
	                byte[] gb2312_bt =
	                    Encoding.GetEncoding("gb2312").GetBytes(new char[] { chr });//GetBytes()方法,{chr}:数组创建必须有数组大小或数组初始值设定项
	                int n = (int)gb2312_bt[0]<<8;//字节序列的第一个字节左移八位
	                n += (int)gb2312_bt[1];     //将第一个自己移八位再与第二个直接相加得到汉字编码
	                OutPutTextBox.Text = Convert.ToString(n,2);
	                //十进制显示:
	                //OutPutTextBox.Text = n.ToString();
	            }
	            catch(Exception)
	            {
	                MessageBox.Show("请输入正确汉字");
	            }
	        }
	    }
	}

程序界面:

posted @ 2018-03-25 22:11  泮聪  阅读(250)  评论(0)    收藏  举报