//CRC位域4表:
const unsigned int CRC16R_A001_Table[16] = {//特别注意Keil C51请用code替换const
0x0000,0xCC01,0xD801,0x1400,0xF001,0x3C00,0x2800,0xE401,0xA001,0x6C00,0x7800,0xB401,0x5000,0x9C01,0x8801,0x4400
};
//CRC位域4查表算法:
unsigned int GetCRC16R_A001_0000_0000_Table(unsigned char *crcBuff, unsigned int crcLen) {
unsigned int i;
unsigned int crc = 0x0000;
unsigned char crcTemp;
for(i = 0; i < (crcLen * 2); i ++) {
if (i & 1) crcTemp = crcBuff[i >> 1] >> 4;
else crcTemp = crcBuff[i >> 1] & 0x0F;
crc = (crc >> 4) ^ CRC16R_A001_Table[(crc & 0x0F) ^ crcTemp];
}
return crc;
}
int main() {
//数据格式:非文本HEX
const unsigned char dataTable[] = {
0x12, 0x34, 0x56
};//特别注意Keil C51请用code替换const
unsigned int crc;
crc = GetCRC16R_A001_0000_0000_Table((unsigned char *)dataTable, sizeof(dataTable));
//表格函数返回crc=0xFB36,与HotWC3运算相同
while(crc | 1);//死循环,请在此处设置断点,验证函数返回值crc是否正确!!!
}
/*
表格函数:
GetCRC16R_A001_0000_0000_Table(unsigned char *crcBuff, unsigned int crcLen);
待校验数据区:
crcBuff[] = {//表格函数内部运算需要的Hex编码
0x12, 0x34, 0x56
}
小表循环次数:
crcLen * 2 = 6次
i = 0; crc = 0x0000(初值);
crcTemp = crcBuff[i >> 1] & 0xf = crcBuff[0] & 0xf = 0x2;
(crc & 0xf) ^ crcTemp = (0x0000 & 0xf) ^ 0x2 = 0x0 ^ 0x2 = 0x2;
CRC16R_A001_Table[0x2] = 0xD801;
crc = (crc >> 4) ^ 0xD801 = (0x0000 >> 4) ^ 0xD801 = 0x0000 ^ 0xD801 = 0xD801;
i = 1; crc = 0xD801;
crcTemp = crcBuff[i >> 1] >> 4 = crcBuff[0] >> 4 = 0x1;
(crc & 0xf) ^ crcTemp = (0xD801 & 0xf) ^ 0x1 = 0x1 ^ 0x1 = 0x0;
CRC16R_A001_Table[0x0] = 0x0000;
crc = (crc >> 4) ^ 0x0000 = (0xD801 >> 4) ^ 0x0000 = 0x0D80 ^ 0x0000 = 0x0D80;
i = 2; crc = 0x0D80;
crcTemp = crcBuff[i >> 1] & 0xf = crcBuff[1] & 0xf = 0x4;
(crc & 0xf) ^ crcTemp = (0x0D80 & 0xf) ^ 0x4 = 0x0 ^ 0x4 = 0x4;
CRC16R_A001_Table[0x4] = 0xF001;
crc = (crc >> 4) ^ 0xF001 = (0x0D80 >> 4) ^ 0xF001 = 0x00D8 ^ 0xF001 = 0xF0D9;
i = 3; crc = 0xF0D9;
crcTemp = crcBuff[i >> 1] >> 4 = crcBuff[1] >> 4 = 0x3;
(crc & 0xf) ^ crcTemp = (0xF0D9 & 0xf) ^ 0x3 = 0x9 ^ 0x3 = 0xA;
CRC16R_A001_Table[0xA] = 0x7800;
crc = (crc >> 4) ^ 0x7800 = (0xF0D9 >> 4) ^ 0x7800 = 0x0F0D ^ 0x7800 = 0x770D;
i = 4; crc = 0x770D;
crcTemp = crcBuff[i >> 1] & 0xf = crcBuff[2] & 0xf = 0x6;
(crc & 0xf) ^ crcTemp = (0x770D & 0xf) ^ 0x6 = 0xD ^ 0x6 = 0xB;
CRC16R_A001_Table[0xB] = 0xB401;
crc = (crc >> 4) ^ 0xB401 = (0x770D >> 4) ^ 0xB401 = 0x0770 ^ 0xB401 = 0xB371;
i = 5; crc = 0xB371;
crcTemp = crcBuff[i >> 1] >> 4 = crcBuff[2] >> 4 = 0x5;
(crc & 0xf) ^ crcTemp = (0xB371 & 0xf) ^ 0x5 = 0x1 ^ 0x5 = 0x4;
CRC16R_A001_Table[0x4] = 0xF001;
crc = (crc >> 4) ^ 0xF001 = (0xB371 >> 4) ^ 0xF001 = 0x0B37 ^ 0xF001 = 0xFB36;
表格函数最终结果(HotWC3的crc = 0xFB36):
crc = crc ^ 出值= 0xFB36 ^ 0x0000 = 0xFB36;
*/
|