C#中如何获得字母的ASCII码?

发布时间 2023-10-12 10:05:13作者: 一路探索者

      ASCII码是计算机的基础,有时编程过程中也要遇到,这里重点介绍0-127之间的ASCII码表。

      0~31及127(共33个)是控制字符和通信专用字符。控制字符,如LF(换行)、CR(回车)、FF(换页)、DEL(删除)、BS(退格)、BEL(响铃)等。通信专用字符,如SOH(文头)、EOT(文尾)、ACK(确认)等。ASCII值为8、9、10 和13 分别转换为退格、制表、换行和回车字符。它们不能显示出来,但会依不同的应用程序,而对文本显示有不同的影响。

      32~126(共95个)是可显字符,其中32是空格;48~57为0到9十个阿拉伯数字;65~90为26个大写英文字母;97~122号为26个小写英文字母,其余为一些标点符号、运算符号等。

      ASCII是0-127的整数,要获取某个字符的ASCII,可以通过Encoding类的ASCII 属性和GetBytes( )方法来实现。

 

      GetBytes( )方法的声明如下:

public virtual byte[] GetBytes(

       char[] chars

)

参数

chars

类型:System.Char[]

包含要编码的字符的字符数组。

返回值

类型:System.Byte[]

一个字节数组,包含对指定的字符集进行编码的结果。

 

public virtual byte[] GetBytes(

       string s

)

参数

s

类型:System.String

返回值

类型:System.Byte[]

一个字节数组,包含对指定的字符集进行编码的结果。

 

public virtual byte[] GetBytes(

       char[] chars,

       int index,

       int count

)

参数

chars

类型:System.Char[]

包含要编码的字符集的字符数组。

index

类型:System.Int32

第一个要编码的字符的索引。

count

类型:System.Int32

要编码的字符的数目。

返回值

类型:System.Byte[]

一个字节数组,包含对指定的字符集进行编码的结果。

 

[CLSCompliantAttribute(false)]

[ComVisibleAttribute(false)]

public virtual int GetBytes(

       char* chars,

       int charCount,

       byte* bytes,

       int byteCount

)

参数

chars

类型:System.Char*

指向第一个要编码的字符的指针。

charCount

类型:System.Int32

要编码的字符的数目。

bytes

类型:System.Byte*

一个指针,指向开始写入所产生的字节序列的位置。

byteCount

类型:System.Int32

最多写入的字节数。

返回值

类型:System.Int32

在由 bytes 参数指示的位置处写入的实际字节数。

 

public abstract int GetBytes(

       char[] chars,

       int charIndex,

       int charCount,

       byte[] bytes,

       int byteIndex

)

参数

chars

类型:System.Char[]

包含要编码的字符集的字符数组。

charIndex

类型:System.Int32

第一个要编码的字符的索引。

charCount

类型:System.Int32

要编码的字符的数目。

bytes

类型:System.Byte[]

要包含所产生的字节序列的字节数组。

byteIndex

类型:System.Int32

开始写入所产生的字节序列的索引位置。

返回值

类型:System.Int32

写入 bytes 的实际字节数。

 

public virtual int GetBytes(

       string s,

       int charIndex,

       int charCount,

       byte[] bytes,

       int byteIndex

)

参数

s

类型:System.String

包含要编码的字符集的 String。

charIndex

类型:System.Int32

第一个要编码的字符的索引。

charCount

类型:System.Int32

要编码的字符的数目。

bytes

类型:System.Byte[]

要包含所产生的字节序列的字节数组。

byteIndex

类型:System.Int32

开始写入所产生的字节序列的索引位置。

返回值

类型:System.Int32

写入 bytes 的实际字节数。

 

      本例的关键代码如下:

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text; //引用Encoding

using System.Windows.Forms;

 

private void button1_Click(object sender, EventArgs e)

{

    if (textBox1.Text == "")

    {

        MessageBox.Show("字母文本框不能为空", "信息", MessageBoxButtons.OK, MessageBoxIcon.Information);

        textBox1.Focus();

    }

    else

    {

        byte[] array = new byte[1];

        Encoding ascii = Encoding.ASCII;

        array = ascii.GetBytes(textBox1.Text.Trim());

        int asciicode = (array[0]);

        textBox2.Text = Convert.ToString(asciicode);

    }

}