1. 数据格式转换
1.1 字符串转化为byte数组
前提待转化的字符串格式为对应的十六进制格式,代码如下:
string str= "";
byte[] lReturnBytes = new byte[str.Length / 2];
for (int i = 0; i < lReturnBytes.Length; i++)
lReturnBytes[i] = Convert.ToByte(str.Substring(i * 2, 2), 16);
1.2 byte数组转化为字符串
代码如下:
byte[] lByteData = new byte[]{0xFF,0x10,0x02,0x03,0x04,0x05};
BitConverter.ToString(lByteData , 0, lByteData.Length).Replace("-", "")
1.3 ASCII码转化为byte型数组
byte gHighByte, gLowByte;
byte[] lSource= new byte[]{0x66,0x66,0x66,0x66,0x34,0x55};
byte[] lDestination= new byte[32]; //长度可按照转换需求自行定义
for (int i = 0; i < lSource.Length; i += 2)
{
gHighByte = lSource[i];
gLowByte = lSource[i + 1];
if (gHighByte > 0x60)
gHighByte -= 0x57;
else if (gHighByte > 0x39)
gHighByte -= 0x37;
else
gHighByte -= 0x30;
if (gLowByte > 0x60)
gLowByte -= 0x57;
else if (gLowByte > 0x39)
gLowByte -= 0x37;
else
gLowByte -= 0x30;
lDestination[i / 2] = (byte)((gHighByte << 4) | gLowByte);
}