1 /*
2 *  C Implementation: crc32
3 *
4 *  code from http://www.w3.org/TR/PNG/#D-CRCAppendix
5 *
6 */
7 
8 /* Table of CRCs of all 8-bit messages. */
9 static unsigned long crc_table[256];
10 
11 /* Flag: has the table been computed? Initially false. */
12 static int crc_table_computed = 0;
13 
14 /* Make the table for a fast CRC. */
make_crc_table(void)15 static void make_crc_table(void)
16 {
17 	unsigned long c;
18 	int n, k;
19 
20 	for (n = 0; n < 256; n++) {
21 		c = (unsigned long) n;
22 		for (k = 0; k < 8; k++) {
23 			if (c & 1)
24 				c = 0xedb88320L ^ (c >> 1);
25 			else
26 				c = c >> 1;
27 		}
28 		crc_table[n] = c;
29 	}
30 	crc_table_computed = 1;
31 }
32 
33 
34 /* Update a running CRC with the bytes buf[0..len-1]--the CRC
35 	should be initialized to all 1's, and the transmitted value
36 	is the 1's complement of the final running CRC (see the
37 	crc() routine below). */
38 
update_crc(unsigned long crc,unsigned char * buf,int len)39 static unsigned long update_crc(unsigned long crc, unsigned char *buf, int len)
40 {
41 	unsigned long c = crc;
42 	int n;
43 
44 	if (!crc_table_computed)
45 		make_crc_table();
46 	for (n = 0; n < len; n++) {
47 		c = crc_table[(c ^ buf[n]) & 0xff] ^ (c >> 8);
48 	}
49 	return c;
50 }
51 
52 /* Return the CRC of the bytes buf[0..len-1]. */
mpc_crc32(unsigned char * buf,int len)53 unsigned long mpc_crc32(unsigned char *buf, int len)
54 {
55 	return update_crc(0xffffffffL, buf, len) ^ 0xffffffffL;
56 }
57