您的位置:首页 > 编程语言 > C#

C#字母与ASCII码的转换

2015-07-25 14:58 441 查看

最后的效果图

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;

using System.Text.RegularExpressions;

namespace WindowsFormsApplication1

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

        private void btn_toascII_Click(object sender, EventArgs e)

        {

            if (txt_char.Text != string.Empty)  //确认textbox的值不为空

            {

                if (Encoding.GetEncoding("unicode").GetBytes(new char[] { txt_char.Text[0] })[1] == 0) //进行加密,最下面有详解

                {

                    txt_ASCII.Text = Encoding.GetEncoding("unicode").GetBytes(txt_char.Text)[0].ToString();

                }

                else

                {

                    txt_ASCII.Text = string.Empty;

                    MessageBox.Show("只能输入字母" + Encoding.GetEncoding("unicode").GetBytes(new char[] { txt_char.Text[0] })[1]);

                }

            }

            

        }

        private void btn_tochar_Click(object sender, EventArgs e)

        {

            if (txt_ASCII.Text != string.Empty)

            {

                int p;

                if (int.TryParse(txt_ASCII.Text, out p))

                {

                    txt_tochar.Text = ((char)p).ToString();

                }

                else

                {

                    MessageBox.Show("请输入正确的ASCII码");

                }

            }

        }

    }

}

本实例在实现时,主要用到了Encoding对象的GetBytes方法

用此方法接受一个字符串或字符数组作为参数,最后返回字节数组,可以根据字节数组得到字母的ASCII码

例如: string p1="abc";

Encoding p2=Encoding.GetBytes("unicode");

byte[] p3=p2.GetBytes(p1);

string p4=p3[0].ToString();

代码中首先使用encoding的方法得到encoding的对象,然后调用encoding对象的getbytes方法,此方法接受一个字符串或字符数组作为参数,最后返回字节数组对象,我们可以根据字节数组的第0个索引来得到字符串中第一个字母的ASCII码。

文件下载地址:http://download.csdn.net/detail/qq_28597703/8932481
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: