![](https://img-blog.csdnimg.cn/img_convert/37a11c5c5929ca6a65560cb1326e066d.jpeg)
本文主要介绍了C#字符串和Acsii码相互转换,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
1,现在因为遇到一个读取pdf文件文本信息遇到乱么问题,才找到这个文本字符串的编码转换的实现方式来判断是否存在乱码(0>乱码>255):
C# 字符转ASCII码,ASCII码转字符
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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." ); } } |
ASCII码转字符:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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 | string str= "abcd" ; byte [] bytetest = System.Text.Encoding.Default.GetBytes(str.ToString()); |
到此这篇关于C#字符串和Acsii码相互转换的文章就介绍到这了,希望可以对你有所帮助。
来源:微点阅读 https://www.weidianyuedu.com