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

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

        /// /// C# 字符转ASCII码/// /// /// 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.");}}/// /// C# ASCII码转字符/// /// /// 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码互转不支持中文字符,使用下面的方法可以进行包含中文字符串的相互转换

        /// /// 含中文字符串转ASCII/// /// /// 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 "";}/// /// ASCII转含中文字符串/// /// ASCII字符串/// 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!

中文字符不再乱码


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部