/// <summary>
/// ASSCII转换字符转
/// </summary>
/// <param name="data">ascii码</param>
public static object AsEncon(string data)
{
byte[] ba = System.Text.ASCIIEncoding.Default.GetBytes(data);
StringBuilder sb = new StringBuilder();
foreach (byte b in ba)
{
sb.Append(b.ToString("X") + " ");
}
//conPrint("AsEncon 转换16hex:" + sb);
return sb;
}
//普通字符串转16进制ASCII码
public static string toASCII(string code)
{
char[] cs = code.ToCharArray();//先转字节数组
string Hstr = null;
for (int l = 0; l < cs.Length; l++)
{
Hstr += ((int)cs[l]).ToString("X")+" ";
}
//System.Console.WriteLine(Hstr);
return Hstr;
}
/// <summary>
/// 16进制ASCII码转普通字符串
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string getASCIItoStr(string str)
{
byte[] bb = Hex2Bytes(str, false);
System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding();
string strCharacter = asciiEncoding.GetString(bb);
Console.WriteLine(strCharacter);
return strCharacter;
}
/// <summary>
/// 先将16进制ASCII码转字节数组
/// </summary>
/// <param name="sHex"></param>
/// <param name="isExchange"></param>
/// <returns></returns>
public static byte[] Hex2Bytes(string sHex, bool isExchange)
{
if (sHex == null || sHex.Length == 0)
return null;
sHex = sHex.Length % 2 == 0 ? sHex : "0" + sHex;
byte[] bRtns = new byte[sHex.Length / 2];
for (int i = 0; i < bRtns.Length; i++)
{
if (isExchange)
bRtns[bRtns.Length - 1 - i] = Convert.ToByte(sHex.Substring(i * 2, 2), 16);
else
bRtns[i] = Convert.ToByte(sHex.Substring(i * 2, 2), 16);
}
return bRtns;
}
}