home *** CD-ROM | disk | FTP | other *** search
/ The C Users' Group Library 1994 August / wc-cdrom-cusersgrouplibrary-1994-08.iso / listings / v_08_12 / 8n12130a < prev    next >
Text File  |  1990-10-19  |  1KB  |  42 lines

  1.  
  2. unsigned short crc16(char *pcDataPtr, unsigned short usLength)
  3. {
  4.   /* this routine calculates a byte-wise CCITT CRC-16 of a block of data of length 
  5.       usLength and pointed to by pcDataPtr */
  6.  
  7.   unsigned short usCrc;
  8.   unsigned short usData;
  9.  
  10.   /* At this point, to facilitate register optimization, we either make a 
  11.      local copy of the global variable that holds the current CRC, 
  12.      or we initialize the local copy to the starting value 0xFFFF.  
  13.      We do the latter if we are using this routine to calculate the CRC of 
  14.      ONLY the block pointed to by pcDataPtr, as in this case. */
  15.  
  16.   usCrc = 0xFFFF;
  17.  
  18.   while(usLength--)
  19.   {
  20.     /* The algorithm requires the data bits in the high byte. */
  21.     usData = (*(pcDataPtr++)) << 8;
  22.  
  23.     /* This block of code calculates the CRC for one byte of data. */
  24.     usCrc  = ((usCrc & 0x00FF) << 8) + (usCrc >> 8);
  25.     usCrc  = usCrc ^ usData;
  26.     usData = usCrc & 0xFF00;
  27.     usData = usData << 4;
  28.     usCrc  = usCrc ^ usData;
  29.     usData = usCrc & 0xFF00;
  30.     usData = usData >> 5;
  31.     usCrc  = usCrc ^ usData;
  32.     usData = usData >> 7;
  33.     usCrc  = usCrc ^ usData;
  34.   };
  35.  
  36.   /* We get the CRC ready for transmission. */
  37.   usCrc  = ~(((usCrc & 0x00FF) << 8) + (usCrc >> 8));
  38.   return(usCrc);
  39. }
  40.  
  41.  
  42.