判断
//判断一个字符串是否为 aa 55 a1 这样的字符串,是的就返回byte个数,否则,返回-1
public int IsHex(string str)
{
int i = 0,len=-1;
//string str = "12312412410afed123";
string pstr = "^";
if (str.Length % 3 == 2) //最后面没有空格
{
len = (str.Length + 1) / 3;
for (i = 0; i < len - 1; i++)
pstr = pstr + "[0-9a-fA-F][0-9a-fA-F][: :]";
pstr = pstr + "[0-9a-fA-F][0-9a-fA-F]";
}
else if (str.Length % 3 == 0) //最后面有空格
{
len = str.Length / 3;
for (i = 0; i < len ; i++)
pstr = pstr + "[0-9a-fA-F][0-9a-fA-F][: :]";
}
else
{
// Console.WriteLine("not");
return -1;
}
// string pstr = "^[0-9a-fA-F][0-9a-fA-F][: :]";
// Console.WriteLine(pstr);
if (System.Text.RegularExpressions.Regex.IsMatch(str, pstr))
{
//是地
//Console.WriteLine("yes");
return len;
}
else
{
return -1;
// Console.WriteLine("not");
}
}
转换
private static byte[] strToToHexByte(string hexString)
{
hexString = hexString.Replace(" ", "");
if ((hexString.Length % 2) != 0)
hexString += " ";
byte[] returnBytes = new byte[hexString.Length / 2];
for (int i = 0; i < returnBytes.Length; i++)
returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
return returnBytes;
}