home *** CD-ROM | disk | FTP | other *** search
/ Garbo / Garbo.cdr / mac / source / aufstols.zoo / aufstools.1 / binhex / crc.c < prev    next >
C/C++ Source or Header  |  1991-02-26  |  1KB  |  82 lines

  1. /*
  2.  * compute the crc used in .hqx files for unxbin
  3.  *
  4.  * David Gentzel, Lexeme Corporation
  5.  *
  6.  * Based on crc code in xbin.c by Darin Adler of TMQ Software.
  7.  */
  8.  
  9. #include <stdio.h>
  10.  
  11. #define BYTEMASK    0xFF
  12. #define WORDMASK    0xFFFF
  13. #define WORDBIT        0x10000
  14.  
  15. #define CRCCONSTANT    0x1021
  16.  
  17. static unsigned int crc;
  18.  
  19. extern void putchar_run();
  20.  
  21. /*
  22.  * Update the crc.
  23.  */
  24. static void docrc(c)
  25. register unsigned int c;
  26. {
  27.     register int i;
  28.     register unsigned long temp = crc;
  29.  
  30.     for (i = 0; i < 8; i++)
  31.     {
  32.     c <<= 1;
  33.     if ((temp <<= 1) & WORDBIT)
  34.         temp = (temp & WORDMASK) ^ CRCCONSTANT;
  35.     temp ^= (c >> 8);
  36.     c &= BYTEMASK;
  37.     }
  38.     crc = temp;
  39. }
  40.  
  41. /*
  42.  * Copy all characters from file in to the current output file computing a crc
  43.  * as we go.  Append 2 byte crc to the output.  in may be NULL (empty file).
  44.  */
  45. void make_file_crc(in)
  46. register FILE *in;
  47. {
  48.     register int c;
  49.  
  50.     crc = 0;
  51.     if (in != NULL)
  52.     while ((c = getc(in)) != EOF)
  53.     {
  54.         putchar_run(c);
  55.         docrc(c);
  56.     }
  57.     docrc(0);
  58.     docrc(0);
  59.     putchar_run((crc >> 8) & BYTEMASK);
  60.     putchar_run(crc & BYTEMASK);
  61. }
  62.  
  63. /*
  64.  * Copy count characters from buffer in to the current output file computing a
  65.  * crc as we go.  Append 2 byte crc to the output.
  66.  */
  67. void make_buffer_crc(in, count)
  68. register unsigned char *in;
  69. register int count;
  70. {
  71.     crc = 0;
  72.     while (count--)
  73.     {
  74.     putchar_run(*in);
  75.     docrc(*in++);
  76.     }
  77.     docrc(0);
  78.     docrc(0);
  79.     putchar_run((crc >> 8) & BYTEMASK);
  80.     putchar_run(crc & BYTEMASK);
  81. }
  82.