串口打印字符串char与hex格式转换
using System;
using System.Text.RegularExpressions;
//hex显示使用空格分开
public static string String2Hex(string input)
{
string output=null;
char[] values = input.ToCharArray();
foreach (char letter in values)
{
int value = Convert.ToInt32(letter);
string hexOutput = String.Format("{0:X2}", value)+" ";
output += hexOutput;
}
return output;
}
public static string strReplace(string input)
{
string output = string.Empty;
foreach (char c in input)
{
//if (c == '\t' || c == '\r' || c == '\n' || c == ' ' )
if(c == ' ')
{
continue;
}
output += c;
}
string s = Regex.Replace(output, @"(((\d{2})|([A-F]\d{1})|(\d{1}[A-F]))(?!$))", "$1 ");//([A-F]\d{1}|\d{2})
return s;
}
public static string Hex2String(string input)
{
string temp = strReplace(input);
string sr = new Regex("[\\s]+").Replace(temp, " ");
//分解成多个字符串
string[] sArray = Regex.Split(sr, " ", RegexOptions.IgnoreCase);
string output = null;
foreach (string str in sArray)
{
UInt32 data = Convert.ToUInt32(str, 16);
output += Convert.ToChar(data);
}
return output;
}