1.将ASCII字符串转为十六进制字节数组()
String input = null;
input = tbxRecvData.Text.ToString().Replace("\t", "");
byte[] readBuffer2 = new byte[(UInt32)System.Text.Encoding.Default.GetBytes(input.ToCharArray()).Length];
readBuffer2 = System.Text.Encoding.Default.GetBytes(input);
tbxRecvData.Text = "";
for (int i = 0; i < (UInt32)System.Text.Encoding.Default.GetBytes(input.ToCharArray()).Length; i++)
{
//String strA = a.ToString("x8");
tbxRecvData.AppendText(readBuffer2[i].ToString("X2") + " ");
}
2.十六进制字符串转为ASCII
String hexValues = tbxRecvData.Text.ToString().Replace("\t", "").Replace("\n", "").Replace("\r", "");
if (hexValues.Length <= 0)
return;
hexValues = hexValues.Trim(); //去字符串首尾空格的函数
//string hexValues = "48 65 6C 6C 6F 20 57 6F 72 6C 64 21";
string[] hexValuesSplit = hexValues.Split(' ');
tbxRecvData.Text = "";
foreach (String hex in hexValuesSplit)
{
// Convert the number expressed in base-16 to an integer.
int value = Convert.ToInt32(hex, 16);
// Get the character corresponding to the integral value.
string stringValue = Char.ConvertFromUtf32(value);
char charValue = (char)value;
tbxRecvData.AppendText(stringValue);
//Console.WriteLine("hexadecimal value = {0}, int value = {1}, char value = {2} or {3}",
//hex, value, stringValue, charValue);
}
/// <summary>
/// 字节数组转16进制字符串
/// </summary>
/// <param name="bytes"></param>
/// <returns></returns>
public static string byteToHexStr(byte[] bytes)
{
string returnStr = "";
if (bytes != null)
{
for (int i = 0; i < bytes.Length; i++)
{
returnStr += bytes[i].ToString("X2");
}
}
return returnStr;
}