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
相关文章推荐
- C# 实现Tree,包含parentId和children
- C# using 三种使用方式
- C#中的反射
- C#中对泛型List进行分组输出元素
- C#实现WinForm随WINDOWS服务一起启动
- C#调用Rar文件及获取Rar返回值的方法
- C#群发邮件
- [转]学习C#:Attribute与Property
- 【转】C#中对IDisposable接口的理解
- 挖一挖C#中那些我们不常用的东西之系列(5)——FlagAttribute
- 看看C# 6.0中那些语法糖都干了些什么(中篇)
- 看看C# 6.0中那些语法糖都干了些什么(上篇)
- C# KeyDown KeyPress KeyUp 处理相应的键盘事件
- 走近,C#
- C# 发送邮件
- C# yield return 流程理解
- 十七、C# 反射、特性和动态编程
- ok6410 LED/GPIO 控制 C#程序
- [转]改善C#程序的建议4:C#中标准Dispose模式的实现
- C#的方法