关于CRC16验证过程
由于要通过SOCKET进行通讯。在应答客户端时要发送一个数据包,包格式如下
EXT --》包头--》0x02
ADDR --》2个字节‘FF’
ACK --》1个字节‘1’
CRC --》2个字节 0x000,0x000
ETX --》包尾--》0x03
我的方法是这样的。
byte[] by = new byte[] { 0x02, (byte)Convert.ToChar("F"), (byte)Convert.ToChar("F"), 1, 0X000,0X000, 0x03 };
GetCrc_16(by, by.Length);
//生成校验码
public static byte[] GetCrc_16(byte[] _bys, int nLength)
{
short cRc_16 = 0x0000; // 初始化
int _index = 0;
while (nLength > 0)
{
cRc_16 = (short)((cRc_16 << 8) ^ crc_tbl[((cRc_16 >> 8) ^ _bys[_index]) & 0xff]);
nLength--;
_index++;
}
Byte[] CRCs = ShortToByte(cRc_16);
_bys[_bys.Length - 3] = CRCs[0];
_bys[_bys.Length - 2] = CRCs[1];
return _bys;
}
//short 转换成BYTE
public static byte[] ShortToByte(short _CRC_16)
{
byte[] b = new byte[2];
b[0] = (byte)((0xff & _CRC_16) >> 8);
b[1] = (byte)(0xff & _CRC_16);
return b;
}
请高手告诉我。是否对的。如果错了。错在哪里?