首页 > orther > notice > C#“字符转成ASCII码,ASCII码转成字符”代码
2011
06-10

C#“字符转成ASCII码,ASCII码转成字符”代码

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
{
throw new Exception("Character is not valid.");
}

}

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
{
throw new Exception("ASCII Code is not valid.");
}
}

学习小结:字符转换成ASCII码函数:Encoding.ASCII.GetBytes(string)
将ASCII码转换成字符:Convert.ToString(Encoding.ASCII.GetString(asciicode))

最后编辑:
作者:admin
捐 赠如果您觉得这篇文章有用处,请支持作者!鼓励作者写出更好更多的文章!

留下一个回复