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 }

 

posted on 2020-05-21 21:20  kyuusan  阅读(10405)  评论(0编辑  收藏  举报