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

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

        /// <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.");
            }
        }

测试:

        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();
        }

结果:

我爱China!
------------
??China!

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

        /// <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 "";
        }

测试:

        static void Main(string[] args)
        {
            string testStr = "我爱China!";
            Console.WriteLine(testStr);
            
            string rtnStr = ASCII2Str(Str2ASCII(testStr));
            Console.WriteLine("------------");
            Console.WriteLine(rtnStr)
            Console.ReadLine();
        }

结果:

我爱China!
------------
我爱China!

中文字符不再乱码

  • 5
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
C#,可以使用以下方法将字符转换ASCII码: 方法一: ```csharp string str = "abc"; StringBuilder ascii = new StringBuilder(); foreach (char c in str) { int asciiValue = (int)c; ascii.Append(asciiValue.ToString() + " "); } string asciiString = ascii.ToString(); Console.WriteLine(asciiString); ``` 这个方法将字符的每个字符转换为对应的ASCII码,并将结果以字符串形式输出。 方法二: ```csharp string str = "abc"; byte\[\] bytes = System.Text.Encoding.ASCII.GetBytes(str); StringBuilder ascii = new StringBuilder(); foreach (byte b in bytes) { ascii.Append(b.ToString() + " "); } string asciiString = ascii.ToString(); Console.WriteLine(asciiString); ``` 这个方法使用`System.Text.Encoding.ASCII.GetBytes()`将字符转换ASCII码的字节数组,然后将每个字节转换为对应的ASCII码,并将结果以字符串形式输出。 希望这个回答对你有帮助!\[1\]\[2\] #### 引用[.reference_title] - *1* *3* [接收的String类型与ASCII码之间的转换](https://blog.csdn.net/Stuomasi_xiaoxin/article/details/129372426)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [C# string ASCII码 16进制转换](https://blog.csdn.net/heihei233/article/details/125346252)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值