标准CRC16
/** *bufData:指令数据 *buflen:处理的指令长度 *pcrc:处理完之后的CRC码 **/ int get_crc16(unsigned char* bufData, unsigned int buflen) { int ret = 0; unsigned short CRC = 0xffff; unsigned short POLYNOMIAL = 0xa001; int i, j; //指令为空 if (bufData == NULL) { return -1; } //校验计算的长度为0 if (buflen == 0) { return ret; } for (i = 0; i < buflen; i++) { CRC ^= bufData[i]; //总共八次右移操作 for (j = 0; j < 8; j++) { if ((CRC & 0x0001) != 0) { //右移的移出位为1 CRC >>= 1; CRC ^= POLYNOMIAL; } else { //右移的移出位为0 CRC >>= 1; } } } printf("CRC=%X\n", CRC); //低位在前,高位在后 unsigned char* pcrc; qDebug() << "pcrc[0] =" << (unsigned char)(CRC & 0x00ff); qDebug() << "pcrc[1] = " <<(unsigned char)(CRC >> 8); return ret; }
#include <iostream> unsigned short CRC16_CCITT_FALSE(unsigned char* puchMsg, unsigned int usDataLen) { unsigned short wCRCin = 0xFFFF; unsigned short wCPoly = 0x1021; unsigned char wChar = 0; while (usDataLen--) { wChar = *(puchMsg++); wCRCin ^= (wChar << 8); for (int i = 0; i < 8; i++) { if (wCRCin & 0x8000) { wCRCin = (wCRCin << 1) ^ wCPoly; } else { wCRCin = wCRCin << 1; } } } return (wCRCin); } //发送 0xAA , 0x06 , 0x10, 0x01 //接受 42991 (A7EF) int main() { unsigned char value[] = { 0xAA , 0x06 , 0x10, 0x01 }; unsigned short result = CRC16_CCITT_FALSE(value, 4); std::cout << result; return 0; }