Watt-32 tcp/ip  2.2 dev-rel.10
crc.c
Go to the documentation of this file.
1 
10 #include <stdio.h>
11 #include <stdlib.h>
12 
13 #include "wattcp.h"
14 #include "misc.h"
15 
16 #define CRC_BITS 32
17 #define CRC_HIBIT ((DWORD) (1L << (CRC_BITS-1)))
18 #define CRC_SHIFTS (CRC_BITS-8)
19 
20 /* Our PRZ's 24-bit CRC generator polynomial. Ref:
21  * http://en.wikipedia.org/wiki/Cyclic_redundancy_check
22  * Section "Commonly used and standardized CRCs"
23  */
24 #define CRC_PRZ 0x864CFBL
25 
26 DWORD *crc_table; /* Pre-generated table for speeding up CRC calculations. */
27 
28 /*
29  * mk_crctbl() derives a CRC lookup table from the CRC polynomial.
30  * The table is used later by crc_bytes() below.
31  * mk_crctbl() only needs to be called once at the dawn of time.
32  * I.e. in crc_init().
33  *
34  * The theory behind mk_crctbl() is that table[i] is initialized
35  * with the CRC of i, and this is related to the CRC of `i >> 1',
36  * so the CRC of `i >> 1' (pointed to by p) can be used to derive
37  * the CRC of i (pointed to by q).
38  */
39 static void mk_crctbl (DWORD poly, DWORD *tab)
40 {
41  DWORD *p = tab;
42  DWORD *q = tab;
43  int i;
44 
45  *q++ = 0;
46  *q++ = poly;
47  for (i = 1; i < 128; i++)
48  {
49  DWORD t = *(++p);
50 
51  if (t & CRC_HIBIT)
52  {
53  t <<= 1;
54  *q++ = t ^ poly;
55  *q++ = t;
56  }
57  else
58  {
59  t <<= 1;
60  *q++ = t;
61  *q++ = t ^ poly;
62  }
63  }
64 }
65 
66 /*
67  * Calculate 32-bit CRC on buffer 'buf' with length 'len'.
68  */
69 DWORD crc_bytes (const char *buf, size_t len)
70 {
71  DWORD accum;
72 
73  for (accum = 0; crc_table && len > 0; len--)
74  accum = (accum << 8) ^ crc_table[(BYTE)(accum >> CRC_SHIFTS) ^ *buf++];
75  return (accum);
76 }
77 
78 BOOL crc_init (void)
79 {
80  if (crc_table)
81  return (TRUE);
82 
83  crc_table = calloc (sizeof(DWORD), 256);
84  if (!crc_table)
85  return (FALSE);
86 
87  mk_crctbl (CRC_PRZ, crc_table);
88  return (TRUE);
89 }
90 
Core definitions.