C# string与ASCII码相互转换及包含中文字符的转换方法

此文章分别转载自C#字符串转换为Acsii码,Ascii转化为字符串和ASP.NET 或C# 中ASCII码含中文字符的编解码处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
        /// <summary>
        /// C# 字符转ASCII码
        /// </summary>
        /// <param name="character"></param>
        /// <returns></returns>
        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.");
            }
        }
        /// <summary>
        /// C# ASCII码转字符
        /// </summary>
        /// <param name="asciiCode"></param>
        /// <returns></returns>
        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.");
            }
        }

测试:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
        static void Main(string[] args)
        {
            string testStr = "我爱China!";
            Console.WriteLine(testStr);
            string[] testString = new string[testStr.Length];
            for (int i = 0; i< testStr.Length; i++)
            {
                testString[i] = testStr.ElementAt(i).ToString();
            }
            StringBuilder stringBuilder = new StringBuilder();
            foreach (var str in testString)
            {
                stringBuilder.Append(Chr(Asc(str)));
            }
            Console.WriteLine("------------");
            Console.WriteLine(stringBuilder.ToString());
            Console.ReadLine();
        }

结果:

1
2
3
我爱China!
------------
??China!

说明以上的字符串和ASCII码互转不支持中文字符,使用下面的方法可以进行包含中文字符串的相互转换

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
        /// <summary>
        /// 含中文字符串转ASCII
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string Str2ASCII(String str)
        {
            try
            {
                //这里我们将采用2字节一个汉字的方法来取出汉字的16进制码
                byte[] textbuf = Encoding.Default.GetBytes(str);
                //用来存储转换过后的ASCII码
                string textAscii = string.Empty;

                for (int i = 0; i < textbuf.Length; i++)
                {
                    textAscii += textbuf[i].ToString("X");
                }
                return textAscii;
            }
            catch (Exception ex)
            {
                Console.WriteLine("含中文字符串转ASCII异常" + ex.Message);
            }
            return "";
        }

        /// <summary>
        /// ASCII转含中文字符串
        /// </summary>
        /// <param name="textAscii">ASCII字符串</param>
        /// <returns></returns>
        public static string ASCII2Str(string textAscii)
        {
            try
            {
                int k = 0;//字节移动偏移量

                byte[] buffer = new byte[textAscii.Length / 2];//存储变量的字节

                for (int i = 0; i < textAscii.Length / 2; i++)
                {
                    //每两位合并成为一个字节
                    buffer[i] = byte.Parse(textAscii.Substring(k, 2), System.Globalization.NumberStyles.HexNumber);
                    k = k + 2;
                }
                //将字节转化成汉字
                return Encoding.Default.GetString(buffer);
            }
            catch (Exception ex)
            {
                Console.WriteLine("ASCII转含中文字符串异常" + ex.Message);
            }
            return "";
        }

测试:

1
2
3
4
5
6
7
8
9
10
        static void Main(string[] args)
        {
            string testStr = "我爱China!";
            Console.WriteLine(testStr);
           
            string rtnStr = ASCII2Str(Str2ASCII(testStr));
            Console.WriteLine("------------");
            Console.WriteLine(rtnStr)
            Console.ReadLine();
        }

结果:

1
2
3
我爱China!
------------
我爱China!

中文字符不再乱码