build: update gnulib submodule to latest
[gzip.git] / sample / makecrc.c
blob8fa2959c6ee44f60f5fd38b47ee618f365fdf073
1 /* Not copyrighted 1990 Mark Adler */
3 #include <config.h>
4 #include <stdio.h>
6 main()
7 /*
8 Generate a table for a byte-wise 32-bit CRC calculation on the polynomial:
9 x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1.
11 Polynomials over GF(2) are represented in binary, one bit per coefficient,
12 with the lowest powers in the most significant bit. Then adding polynomials
13 is just exclusive-or, and multiplying a polynomial by x is a right shift by
14 one. If we call the above polynomial p, and represent a byte as the
15 polynomial q, also with the lowest power in the most significant bit (so the
16 byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
17 where a mod b means the remainder after dividing a by b.
19 This calculation is done using the shift-register method of multiplying and
20 taking the remainder. The register is initialized to zero, and for each
21 incoming bit, x^32 is added mod p to the register if the bit is a one (where
22 x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by
23 x (which is shifting right by one and adding x^32 mod p if the bit shifted
24 out is a one). We start with the highest power (least significant bit) of
25 q and repeat for all eight bits of q.
27 The table is simply the CRC of all possible eight bit values. This is all
28 the information needed to generate CRC's on data a byte at a time for all
29 combinations of CRC register values and incoming bytes. The table is
30 written to stdout as 256 long hexadecimal values in C language format.
33 unsigned long c; /* crc shift register */
34 unsigned long e; /* polynomial exclusive-or pattern */
35 int i; /* counter for all possible eight bit values */
36 int k; /* byte being shifted into crc apparatus */
38 /* terms of polynomial defining this crc (except x^32): */
39 static int p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};
41 /* Make exclusive-or pattern from polynomial (0xedb88320) */
42 e = 0;
43 for (i = 0; i < sizeof(p)/sizeof(int); i++)
44 e |= 1L << (31 - p[i]);
46 /* Compute and print table of CRC's, five per line */
47 printf(" 0x00000000L");
48 for (i = 1; i < 256; i++)
50 c = i;
51 /* The idea to initialize the register with the byte instead of
52 * zero was stolen from Haruhiko Okumura's ar002
54 for (k = 8; k; k--)
55 c = c & 1 ? (c >> 1) ^ e : c >> 1;
56 printf(i % 5 ? ", 0x%08lxL" : ",\n 0x%08lxL", c);
58 putchar('\n');
59 return 0;