home *** CD-ROM | disk | FTP | other *** search
/ Source Code 1992 March / Source_Code_CD-ROM_Walnut_Creek_March_1992.iso / usenet / altsrcs / 3 / 3600 / addbfcrc.c next >
C/C++ Source or Header  |  1991-07-10  |  1KB  |  63 lines

  1. /* adbfcrc.c */
  2.  
  3. /*
  4. addbfcrc() accepts a buffer address and a count and adds the CRC for
  5. all bytes in the buffer to the global variable crccode using
  6. CRC-16.
  7.  
  8. This file is public domain.
  9.  
  10.                                     -- Rahul Dhesi 1991/07/07
  11. */
  12.  
  13. #define TABLEN    256
  14.  
  15. unsigned int crccode;
  16. unsigned int crctab[TABLEN];
  17.  
  18. int addbfcrc(buffer,count)
  19. char *buffer;
  20. unsigned count;
  21.  
  22. {
  23.    register unsigned int localcrc;
  24.    register int i;
  25.    localcrc = crccode;
  26.  
  27.    for (i=0; i<count; i++)
  28.       localcrc = (localcrc>>8) ^ crctab[(localcrc ^ (buffer[i])) & 0x00ff];
  29.    crccode = localcrc;
  30. }
  31.  
  32. /* gentab() generates table for CRC calculation, as described in
  33. "C Programmer's Guide to Serial Communications" by Joe Campbell */
  34.  
  35. /* reverse CRC-16 polynomial */
  36. #define CRC_FUNC        (unsigned) 0xa001
  37.  
  38. unsigned int calcterm();
  39.  
  40. unsigned int calcterm (data)
  41. register unsigned int data;
  42. {
  43.    int i;
  44.    register unsigned int accum = 0;
  45.  
  46.    data <<= 1;
  47.    for (i = 8;  i > 0;  i--) {
  48.       data >>= 1;
  49.       if ((data ^ accum) & 0x0001)
  50.          accum = (accum >> 1) ^ CRC_FUNC;
  51.       else
  52.          accum >>= 1;
  53.    }
  54.    return accum;
  55. }
  56.  
  57. int gentab()
  58. {
  59.    register unsigned int i;
  60.    for (i = 0;  i < TABLEN;  i++)
  61.       crctab[i] = calcterm (i);
  62. }
  63.