#ifndef _CRC32_H_
#define _CRC32_H_
typedef unsigned char u8;
typedef unsigned short u16;
typedef unsigned long u32;
#define ARRAY_SIZE(x) ((sizeof(x))/(sizeof(x[0])))
#define CRC_NORMAL 0x00
#define CRC_REVERSE 0x01
#define CRC32_0X04C11DB7 0x04c11db7
#define CRC32_0xEDB88320 0xedb88320
extern void crc_init(u8 flag, u32 poly);
extern u32 crc_calc(u8 flag, u32 init_value, u8 *ptr, u32 len);
#endif /* crc32.h */
#include "crc32.h"
static u32 crc_tbl[256] = { 0 };
extern void crc_init(u8 flag, u32 poly)
{
u16 i, j;
u32 tmp = 0;
for (i = 0; i < 256; i++) {
tmp = i;
if (CRC_NORMAL == flag) {
tmp = tmp << 24;
for (j = 0; j < 8; j ++) {
if (tmp & 0x80000000) {
tmp = (tmp << 1) ^ poly;
} else {
tmp = tmp << 1;
}
}
} else {
for (j = 0; j < 8; j ++) {
if (tmp & 0x00000001) {
tmp = (tmp >> 1) ^ poly;
} else {
tmp = tmp >> 1;
}
}
}
crc_tbl[i] = tmp;
}
}
extern u32 crc_calc(u8 flag, u32 init_value, u8 *ptr, u32 len)
{
u32 crc_res;
if (NULL == ptr)
goto err_ptr;
if (0 == len)
goto err_len;
crc_res = init_value;
if (CRC_NORMAL == flag) {
while (len --) {
crc_res = crc_tbl[((crc_res >> 24) ^ *ptr) & 0xFF] ^ ((crc_res << 8) & 0xFFFFFF00);
ptr ++;
}
} else {
while (len --) {
crc_res = crc_tbl[(crc_res ^ *ptr) & 0xFF] ^ ((crc_res >> 8) & 0x00FFFFFF);
ptr ++;
}
crc_res = crc_res ^ 0xFFFFFFFF;
}
err_ptr:
err_len:
return (crc_res);
}
#if 0
crc_init(CRC_NORMAL, CRC32_0X04C11DB7);
#else
crc_init(CRC_REVERSE, CRC32_0xEDB88320);
#endif
printf("crc = %x\n", crc_calc(CRC_REVERSE, 0xFFFFFFFF, ch8_test, ARRAY_SIZE(ch8_test)));
#if 0
for (u16 i = 0; i < 256; i++) {
printf("0x%08X\n", crc_tbl[i]);
}
#endif
#define cb_CRC_POLY 0x2F
u8 calc_crc8(u8 *data_byte_array, u8 data_byte_array_size)
{
u8 byte_index, bit_index;
u8 crc = 0xFF;
for (byte_index = 0; byte_index < data_byte_array_size; ++ byte_index) {
crc ^= data_byte_array[byte_index];
for (bit_index = 0; bit_index < 8; ++ bit_index) {
if ((crc & 0x80) != 0)
crc = (crc << 1) ^ cb_CRC_POLY;
else
crc = (crc << 1);
}
}
return 0xFF ^ crc;
}