C# ascii码与字符的转换

using System;
using System.Text;

namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("输入要转为ascii码的字符");

string a = Console.ReadLine();
try
{
Console.WriteLine(Asc(a));
}
catch (Exception e){

Console.WriteLine(e.ToString());
}
Console.WriteLine("输入要转为字符的ascii码");

string b = Console.ReadLine();

try
{
Console.WriteLine(Cha(b));
}
catch (Exception e)
{

Console.WriteLine(e.ToString());
}

}


/*字符转ascii码*/
private static int Asc(string s)
{
if (s.Length == 1)
{

ASCIIEncoding a = new ASCIIEncoding();
int b = (int)a.GetBytes(s)[0];
return b;

}
else {

throw new Exception("String is not vaild");

}
}


/*ascii码转字符*/
private static char Cha(string s)
{

int a = int.Parse(s);
if (a>=0 && a<=255)
{

char c = (char)a;
return c;
}
else
{

throw new Exception("String is not vaild");

}
}

}


}

猜你喜欢

转载自www.cnblogs.com/kyuusan/p/12933664.html