精华区 [关闭][返回]

当前位置:网易精华区>>讨论区精华>>编程开发>>C/C++>>编码解码>>共享点代码给大家——关于CRC(1/2)

主题:共享点代码给大家——关于CRC(1/2)
发信人: riffle(罗慢)
整理人: wenbobo(2002-12-21 22:44:44), 站内信件
// ********************** START OF CRC.H **********************
//
// This header file contains the definitions for the two CRC
// classes, Crc16 and Crc32.
//

#ifndef _CRC_DOT_H
#define _CRC_DOT_H

// The two CRC objects create 16 and 32 bit CRC values using the
// polynomials used by ZMODEM.  The calculations are table driven,
// with the table being initialized by the constructor at runtime.
// The constructor assigns an initial value to the crc, and then
// it is updated on a character by character basis.

class Crc32
{
private:
  static unsigned long table[ 256 ];
  static int initialized;
  unsigned long crc;
public:
  Crc32( unsigned long init_value );
  void update( int c );
  unsigned long value( void )
  {
    return crc;
  }
};

inline void Crc32::update( int c )
{
  crc = table[ ( (int) crc ^ ( c & 0xff ) ) & 0xff ] ^
  ( ( crc >> 8 ) & 0x00FFFFFFL );
}

class Crc16
{
private:
  static unsigned short table[ 256 ];
  static int initialized;
  unsigned short crc;
public:
  Crc16( unsigned short init_value );
  void update( int c );
  unsigned short value( void )
  {
    return crc;
  }
};

inline void Crc16::update( int c )
{
  crc = ( unsigned short ) ( table[ (( crc >> 8 ) & 0xff ) ] ^
  ( crc << 8 ) ^ ( c & 0xff ) );
}

#endif // #ifndef _CRC_DOT_H

// ************************ END OF CRC.H ************************

[关闭][返回]