将字节数组转换成字符串,便于查看记录通讯协议中的指令。
byte[] data = new byte[8] {0x01,0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 };
string str = byteToHexStr(data); //0102030405060708
//方法一
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;
}
//方法二
public static string byteToHexString(byte[] haxS)
{
string resStr = string.Empty;
resStr = BitConverter.ToString(haxS); //格式: 01-02-03-04-05-06-07-08
resStr = resStr.Replace("-","");
return resStr;
}