home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / snip9707.zip / CRC_16.C < prev    next >
C/C++ Source or Header  |  1997-07-05  |  1KB  |  42 lines

  1. /* +++Date last modified: 05-Jul-1997 */
  2.  
  3. #define POLY 0x8408
  4. /*
  5. //                                      16   12   5
  6. // this is the CCITT CRC 16 polynomial X  + X  + X  + 1.
  7. // This works out to be 0x1021, but the way the algorithm works
  8. // lets us use 0x8408 (the reverse of the bit pattern).  The high
  9. // bit is always assumed to be set, thus we only use 16 bits to
  10. // represent the 17 bit value.
  11. */
  12.  
  13. #include "crc.h"
  14.  
  15. WORD crc16(char *data_p, WORD length)
  16. {
  17.       unsigned char i;
  18.       unsigned int data;
  19.       unsigned int crc = 0xffff;
  20.  
  21.       if (length == 0)
  22.             return (~crc);
  23.  
  24.       do
  25.       {
  26.             for (i=0, data=(unsigned int)0xff & *data_p++;
  27.                  i < 8; 
  28.                  i++, data >>= 1)
  29.             {
  30.                   if ((crc & 0x0001) ^ (data & 0x0001))
  31.                         crc = (crc >> 1) ^ POLY;
  32.                   else  crc >>= 1;
  33.             }
  34.       } while (--length);
  35.  
  36.       crc = ~crc;
  37.       data = crc;
  38.       crc = (crc << 8) | ((data >> 8) & 0xff);
  39.  
  40.       return (crc);
  41. }
  42.