crc32/crc32.c

79 lines
1.6 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.
*/
#include <stdlib.h>
typedef unsigned long ulong;
#include "crc32.h"
int crc_big_endian = 0;
ulong crc_polynomial = 0x04C11DB7;
enum {
TABLE_SIZE = 0x100
};
static ulong crc_be_table[TABLE_SIZE]; /* big endian */
static ulong crc_le_table[TABLE_SIZE]; /* little endian */
ulong crc_reflect(ulong input)
{
ulong reflected = 0;
int i;
for (i = 0; i < 4 * 8; i++) {
reflected <<= 1;
reflected |= input & 1;
input >>= 1;
}
return reflected;
}
2012-08-05 19:03:40 -07:00
static void crc_fill_table(int big)
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 */
ulong poly = (big) ? crc_polynomial : crc_reflect(crc_polynomial);
ulong *tc = (big) ? crc_be_table : crc_le_table;
int c, i;
2012-08-04 10:03:16 -07:00
2012-08-05 19:03:40 -07:00
for (c = 0; c < TABLE_SIZE; c++, tc++) {
*tc = (big) ? c << 24 : c;
2012-08-04 10:03:16 -07:00
for (i = 0; i < 8; i++) {
2012-08-05 19:03:40 -07:00
if (*tc & lsb) {
*tc = (big) ? *tc << 1 : *tc >> 1;
*tc ^= poly;
2012-08-04 10:03:16 -07:00
} else {
2012-08-05 19:03:40 -07:00
*tc = (big) ? *tc << 1 : *tc >> 1;
2012-08-04 10:03:16 -07:00
}
2012-08-05 19:03:40 -07:00
*tc &= 0xFFFFFFFF;
2012-08-04 10:03:16 -07:00
}
}
}
2012-08-05 19:24:31 -07:00
void crc_be_cycle(ulong *remainder, char c)
2012-08-04 10:03:16 -07:00
{
static char filled = 0;
2012-08-05 19:24:31 -07:00
ulong byte;
if (!filled) {
2012-08-05 19:03:40 -07:00
crc_fill_table(1);
2012-08-05 19:24:31 -07:00
filled = 1;
2012-08-04 10:03:16 -07:00
}
2012-08-05 19:24:31 -07:00
byte = crc_be_table[((*remainder) >> 24) ^ c];
*remainder = (((*remainder) << 8) ^ byte) & 0xFFFFFFFF;
2012-08-04 10:03:16 -07:00
}
2012-08-05 19:24:31 -07:00
void crc_le_cycle(ulong *remainder, char c)
2012-08-04 10:03:16 -07:00
{
2012-08-05 19:24:31 -07:00
static char filled = 0;
ulong byte;
if (!filled) {
crc_fill_table(0);
filled = 1;
2012-08-04 10:03:16 -07:00
}
2012-08-05 19:24:31 -07:00
byte = crc_le_table[((*remainder) ^ c) & 0xFF];
*remainder = ((*remainder) >> 8) ^ byte;
2012-08-04 10:03:16 -07:00
}