首页 > 代码库 > C# 字符转ASCII码,ASCII码转字符

C# 字符转ASCII码,ASCII码转字符

其实很简单就是使用ASCIIEncoding类相互转化一下,下面我提供两个方法大这看一下吧
1.字符转ASCII码

public static int Asc(string character)   {    if (character.Length == 1)    {     System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();     int intAsciiCode = (int)asciiEncoding.GetBytes(character)[0];     return (intAsciiCode);    }    else    {      return -1 //长度小于1    }   }

2.ASCII转字符串

public static string Chr(int asciiCode)   {    if (asciiCode >= 0 && asciiCode <= 255)    {     System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();     byte[] byteArray = new byte[] { (byte)asciiCode };     string strCharacter = asciiEncoding.GetString(byteArray);     return (strCharacter);    }    else    {     return “格式不正确”;    }

 

C# 字符转ASCII码,ASCII码转字符