C#ascii码与字符的转换 1using System;
2using System.Text;
3
4namespace ConsoleApp1
5 {
6class Program
7 {
8static void Main(string[] args)
9 {
10 Console.WriteLine("输⼊要转为ascii码的字符");
11string a = Console.ReadLine(); //接收字符串
12try
13 {
14 Console.WriteLine(Asc(a)); //将字符串转为ascii码并打印
15 }
16catch (Exception e)
17 {
18 Console.WriteLine(e.ToString());
19 }
20 Console.WriteLine("输⼊要转为字符的ascii码");
21string b = Console.ReadLine(); //接收ascii码
22try
23 {
24 Console.WriteLine(Cha(b)); //将ascii码字符串转为并打印
25 }
26catch (Exception e)
27 {
28 Console.WriteLine(e.ToString());
29 }
30 }
31
32/*字符转ascii码*/
33private static int Asc(string s)
34 {
35if (s.Length == 1)
36 {
37 ASCIIEncoding a = new ASCIIEncoding();
38int b = (int)a.GetBytes(s)[0]; //利⽤ASCIIEncoding类的GetByte()⽅法转码
39return b;
40 }
41else
42 {
43throw new Exception("String is not vaild");
44 }
45 }
46
47/*ascii码转字符*/
48private static char Cha(string s)
49 {
50int a = int.Parse(s); //现将字符串转成int类型
51if (a >= 0 && a <= 255) //若不在这个范围内,则不是字符
52 {
53char c = (char)a; //利⽤类型强转得到字符
54return c;
55 }
a的ascii的编码是多少
56else
57 {
58throw new Exception("String is not vaild");
59 }
60 }
61 }
62 }
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论