using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RS.Common { /// /// ASCII 帮助类 /// public static class ASCIIHelper { /// /// 含中文字符串转ASCII /// /// /// public static string Str2ASCII(String str) { //这里我们将采用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; } /// /// ASCII转含中文字符串 /// /// ASCII字符串 /// public static string ASCII2Str(string textAscii) { 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); } /// /// 16进制转字符串 /// /// /// public static string int16ToASCII(string hexNumber) { //int decimalValue = Convert.ToInt32(hexNumber, 16); // 将十六进制转换为十进制 string binaryString = Convert.ToString(Convert.ToInt32(hexNumber), 2); // 将十进制转换为二进制 int length = binaryString.Length; // 确保二进制字符串的长度是8的倍数 int xlength = length % 8; if (length % 8 != 0) { for (int i = 0; i < 8 - xlength; i++) { binaryString = "0" + binaryString; } } // 分割二进制字符串为每8位一组 string[] binaryChunks = new string[length / 8]; for (int i = 0; i < binaryChunks.Length; i++) { binaryChunks[i] = binaryString.Substring(i * 8, 8); } // 转换每个二进制组为ASCII字符 char[] asciiCharacters = new char[binaryChunks.Length]; for (int i = 0; i < binaryChunks.Length; i++) { int asciiValue = Convert.ToInt32(binaryChunks[i], 2); asciiCharacters[i] = (char)asciiValue; } // 将字符数组转换为字符串 string asciiString = new string(asciiCharacters); if (asciiString.Length < 2) { asciiString = "0" + asciiString; } return asciiString; } } }