//字符转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.");
}
}
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.");
}
}
//另一种写法
string str="abcd";
byte[] bytetest = System.Text.Encoding.Default.GetBytes(str.ToString());
博客展示了C#中字符与ASCII码相互转换的代码。提供了字符转ASCII码和ASCII码转字符的方法,还给出了另一种获取字符串字节数组的写法,若输入不符合要求会抛出异常。

1326

被折叠的 条评论
为什么被折叠?



