1. 代码
public string BytesToHexString(byte[] bytes,int offset, int length)
{
string hexString = string.Empty;
if((bytes != null) && (length != 0))
{
StringBuilder strB = new StringBuilder();
for(int i=offset;i<length+offset;i++)
{
strB.Append(bytes[i].ToString("X2"));
}
hexString = strB.ToString();
}
return hexString;
}
public byte[] StringToHexbytes(string hexString)
{
if (hexString == null) return null;
hexString = hexString.Replace(" ","");
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;
}
2. 测试
byte[] a = new byte[] {0x13,0xAB,0xEF };
string str = BytesToHexString(a,0,3);
byte[] b = StringToHexbytes(str);