参考,(159条消息) CRC16常见几个标准的算法及C语言实现_leumber的博客-CSDN博客_crc16
#include<stdio.h> /****************************Info********************************************** * Name: InvertUint8 * Note: 把字节颠倒过来,如0x12变成0x48 0x12: 0001 0010 0x48: 0100 1000 *****************************************************************************/ void InvertUint8(unsigned char *dBuf,unsigned char *srcBuf) { int i; unsigned char tmp[4]={0}; for(i=0;i< 8;i++) { if(srcBuf[0]& (1 << i)) tmp[0]|=1<<(7-i); } dBuf[0] = tmp[0]; } void InvertUint16(unsigned short *dBuf,unsigned short *srcBuf) { int i; unsigned short tmp[4]={0}; for(i=0;i< 16;i++) { if(srcBuf[0]& (1 << i)) tmp[0]|=1<<(15 - i); } dBuf[0] = tmp[0]; } /****************************Info********************************************** * Name: CRC-16/CCITT x16+x12+x5+1 * Width: 16 * Poly: 0x1021 * Init: 0x0000 * Refin: True * Refout: True * Xorout: 0x0000 * Alias: CRC-CCITT,CRC-16/CCITT-TRUE,CRC-16/KERMIT *****************************************************************************/ unsigned short CRC16_CCITT(unsigned char *data, unsigned int datalen) { unsigned short wCRCin = 0x0000; unsigned short wCPoly = 0x1021; unsigned char wChar = 0; while (datalen--) { wChar = *(data++); InvertUint8(&wChar,&wChar); wCRCin ^= (wChar << 8); for(int i = 0;i < 8;i++) { if(wCRCin & 0x8000) wCRCin = (wCRCin << 1) ^ wCPoly; else wCRCin = wCRCin << 1; } } InvertUint16(&wCRCin,&wCRCin); return (wCRCin); } int main() { unsigned char buf[2]={1,2}; unsigned short crc16=CRC16_CCITT(buf, 2); printf("%x", crc16); }
标签:srcBuf,unsigned,0x12,char,CRC,计算,0x48 From: https://www.cnblogs.com/yanhc/p/16997540.html