Merge branch 'collin' into collin+newconf+sdl
[grub2/phcoder.git] / lib / crc.c
blobbc0d8aa8d0d4d96dfefd73c7acc46deb1312f382
1 /* crc.c - crc function */
2 /*
3 * GRUB -- GRand Unified Bootloader
4 * Copyright (C) 2008 Free Software Foundation, Inc.
6 * GRUB is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * GRUB is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with GRUB. If not, see <http://www.gnu.org/licenses/>.
20 #include <grub/types.h>
21 #include <grub/lib/crc.h>
23 static grub_uint32_t crc32_table [256];
25 static void
26 init_crc32_table (void)
28 auto grub_uint32_t reflect (grub_uint32_t ref, int len);
29 grub_uint32_t reflect (grub_uint32_t ref, int len)
31 grub_uint32_t result = 0;
32 int i;
34 for (i = 1; i <= len; i++)
36 if (ref & 1)
37 result |= 1 << (len - i);
38 ref >>= 1;
41 return result;
44 grub_uint32_t polynomial = 0x04c11db7;
45 int i, j;
47 for(i = 0; i < 256; i++)
49 crc32_table[i] = reflect(i, 8) << 24;
50 for (j = 0; j < 8; j++)
51 crc32_table[i] = (crc32_table[i] << 1) ^
52 (crc32_table[i] & (1 << 31) ? polynomial : 0);
53 crc32_table[i] = reflect(crc32_table[i], 32);
57 grub_uint32_t
58 grub_getcrc32 (grub_uint32_t crc, void *buf, int size)
60 int i;
61 grub_uint8_t *data = buf;
63 if (! crc32_table[1])
64 init_crc32_table ();
66 crc^= 0xffffffff;
68 for (i = 0; i < size; i++)
70 crc = (crc >> 8) ^ crc32_table[(crc & 0xFF) ^ *data];
71 data++;
74 return crc ^ 0xffffffff;