crc32/crc32.c

56 lines
1.3 KiB
C
Raw Normal View History

2012-08-04 10:03:16 -07:00
/* Copyright (C) 2012 Connor Olding
*
* This program is licensed under the terms of the MIT License, and
* is distributed without any warranty. You should have received a
* copy of the license along with this program; see the file LICENSE.
*/
typedef unsigned long ulong;
#include "crc32.h"
2015-04-11 10:34:48 -07:00
ulong
crc_reflect(ulong input)
2012-08-04 10:03:16 -07:00
{
ulong reflected = 0;
2015-04-11 10:34:48 -07:00
for (int i = 0; i < 4 * 8; i++) {
2012-08-04 10:03:16 -07:00
reflected <<= 1;
reflected |= input & 1;
input >>= 1;
}
return reflected;
}
2015-04-11 10:34:48 -07:00
void
crc_fill_table(ulong *table, int big, ulong polynomial)
2012-08-04 10:03:16 -07:00
{
2012-08-05 19:03:40 -07:00
ulong lsb = (big) ? 1 << 31 : 1; /* least significant bit */
2012-08-05 19:58:43 -07:00
ulong poly = (big) ? polynomial : crc_reflect(polynomial);
2012-08-04 10:03:16 -07:00
2015-04-11 10:34:48 -07:00
for (int c = 0; c < CRC_TABLE_SIZE; c++, table++) {
2012-08-05 19:58:43 -07:00
*table = (big) ? c << 24 : c;
2015-04-11 10:34:48 -07:00
for (int i = 0; i < 8; i++) {
2012-08-05 19:58:43 -07:00
if (*table & lsb) {
*table = (big) ? *table << 1 : *table >> 1;
*table ^= poly;
2012-08-04 10:03:16 -07:00
} else {
2012-08-05 19:58:43 -07:00
*table = (big) ? *table << 1 : *table >> 1;
2012-08-04 10:03:16 -07:00
}
2012-08-05 19:58:43 -07:00
*table &= 0xFFFFFFFF;
2012-08-04 10:03:16 -07:00
}
}
}
2015-04-11 10:34:48 -07:00
void
crc_be_cycle(ulong *table, ulong *remainder, char c)
2012-08-04 10:03:16 -07:00
{
ulong byte = table[(((*remainder) >> 24) ^ c) & 0xff];
2012-08-05 19:24:31 -07:00
*remainder = (((*remainder) << 8) ^ byte) & 0xFFFFFFFF;
2012-08-04 10:03:16 -07:00
}
2015-04-11 10:34:48 -07:00
void
crc_le_cycle(ulong *table, ulong *remainder, char c)
2012-08-04 10:03:16 -07:00
{
2012-08-05 19:58:43 -07:00
ulong byte = table[((*remainder) ^ c) & 0xFF];
2012-08-05 19:24:31 -07:00
*remainder = ((*remainder) >> 8) ^ byte;
2012-08-04 10:03:16 -07:00
}