/// <summary>
/// CRC16
/// </summary>
/// <param name="data">要进行计算的数组</param>
/// <returns>计算后的数组</returns>
private static byte[] CRC16(byte[] data)
{
byte[] returnVal = new byte[2];
byte CRC16Lo, CRC16Hi, CL, CH, SaveHi, SaveLo;
int i, Flag;
CRC16Lo = 0xFF;
CRC16Hi = 0xFF;
CL = 0x86;
CH = 0x68;
for (i = 0; i < data.Length; i++)
{
CRC16Lo = (byte)(CRC16Lo ^ data[i]);//每一个数据与CRC寄存器进行异或
for (Flag = 0; Flag <= 7; Flag++)
{
SaveHi = CRC16Hi;
SaveLo = CRC16Lo;
CRC16Hi = (byte)(CRC16Hi >> 1);//高位右移一位
CRC16Lo = (byte)(CRC16Lo >> 1);//低位右移一位
if ((SaveHi & 0x01) == 0x01)//如果高位字节最后一位为
{
CRC16Lo = (byte)(CRC16Lo | 0x80);//则低位字节右移后前面补 否则自动补0
}
if ((SaveLo & 0x01) == 0x01)//如果LSB为1,则与多项式码进行异或
{
CRC16Hi = (byte)(CRC16Hi ^ CH);
CRC16Lo = (byte)(CRC16Lo ^ CL);
}
}
}
returnVal[0] = CRC16Hi;//CRC高位
returnVal[1] = CRC16Lo;//CRC低位
return returnVal;
}