1 using System; 2 using System.Text; 3 4 namespace ConsoleApp1 5 { 6 class Program 7 { 8 static void Main(string[] args) 9 { 10 Console.WriteLine("輸入要轉為ascii碼的字符"); 11 string a = Console.ReadLine(); //接收字符串 12 try 13 { 14 Console.WriteLine(Asc(a)); //將字符串轉為ascii碼並打印 15 } 16 catch (Exception e) 17 { 18 Console.WriteLine(e.ToString()); 19 } 20 Console.WriteLine("輸入要轉為字符的ascii碼"); 21 string b = Console.ReadLine(); //接收ascii碼 22 try 23 { 24 Console.WriteLine(Cha(b)); //將ascii碼字符串轉為並打印 25 } 26 catch (Exception e) 27 { 28 Console.WriteLine(e.ToString()); 29 } 30 } 31 32 /*字符轉ascii碼*/ 33 private static int Asc(string s) 34 { 35 if (s.Length == 1) 36 { 37 ASCIIEncoding a = new ASCIIEncoding(); 38 int b = (int)a.GetBytes(s)[0]; //利用ASCIIEncoding類的GetByte()方法轉碼 39 return b; 40 } 41 else 42 { 43 throw new Exception("String is not vaild"); 44 } 45 } 46 47 /*ascii碼轉字符*/ 48 private static char Cha(string s) 49 { 50 int a = int.Parse(s); //現將字符串轉成int類型 51 if (a >= 0 && a <= 255) //若不在這個范圍內,則不是字符 52 { 53 char c = (char)a; //利用類型強轉得到字符 54 return c; 55 } 56 else 57 { 58 throw new Exception("String is not vaild"); 59 } 60 } 61 } 62 }