//============================================= // 关于CRC计算,到网上一搜,**一大把。经整理,得到如下几段代码。 // 用这几个函数算出来的值是不同的.其中1和2只是反转的关系。 // 按照对crc16的定义,只应存在两种算法。 // 那么3和4怎么理解? // 代码3生成的CRC和MODEBUS协议吻合。 // 本人愚蠢,请指教 //============================================= // 参数说明: 指针、数据长度、初值、多项式 //============================================= // Description: Calc CRC16. // Para: pointer of data. length of data, Init value, Poly // return: result //============================================= unsigned int CRC16_1( unsigned char * puchMsg, unsigned int usDataLen, unsigned int CrcInit, unsigned int Ploy ) { unsigned int crc; unsigned char i;
crc = CrcInit; while( usDataLen-- ) { for( i = 0x80; i != 0; i /= 2 ) { if( ( crc & 0x8000 ) != 0 ) { crc <<= 1; crc ^= Ploy; } else crc <<= 1; if( * puchMsg & i ) crc ^= Ploy; } puchMsg++; } return( crc ); } //============================================= // Description: Calc CRC16. // Para: pointer of data. length of data, Init value, Poly // return: result //============================================= unsigned int CRC16_2( unsigned char * puchMsg, unsigned int usDataLen, unsigned int CrcInit, unsigned int Ploy ) { unsigned int crc; unsigned char i;
crc = CrcInit; while( usDataLen-- ) { for( i = 0x01; i != 0; i *= 2 ) { if( ( crc & 0x0001 ) != 0 ) { crc >>= 1; crc ^= Ploy; } else crc >>= 1; if( * puchMsg & i ) crc ^= Ploy; } puchMsg++; } return( crc ); } //============================================= // Description: Calc CRC16. // Para: pointer of data. length of data, Init value, Poly // return: result //============================================= unsigned int CRC16_3( unsigned char * puchMsg, unsigned int usDataLen, unsigned int CrcInit, unsigned int Ploy ) { unsigned int Crc; int i = 0; unsigned char j = 0;
Crc = CrcInit; for( i = 0; i < usDataLen; i++ ) { Crc ^= puchMsg; for( j = 0; j < 8; j++ ) { if( Crc & 0x0001 ) { Crc >>= 1; Crc ^= Ploy; } else { Crc >>= 1; } } } return ( Crc ); } //============================================= // Description: Calc CRC16. // Para: pointer of data. length of data, Init value, Poly // return: result //============================================= unsigned int CRC16_4( unsigned char * puchMsg, unsigned int usDataLen, unsigned int CrcInit, unsigned int Ploy ) { unsigned int Crc; int i = 0; unsigned char j = 0;
Crc = CrcInit; for( i = 0; i < usDataLen; i++ ) { Crc ^= puchMsg; for( j = 0; j < 8; j++ ) { if( Crc & 0x0001 ) { Crc >>= 1; Crc ^= Ploy; } else { Crc >>= 1; } } } return ( Crc ); } //============================================= |