16位循环冗余校验
忘记最初的源码是从哪里获取的了,保存下代码用于备忘
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
typedef unsigned long u32;
typedef unsigned short u16;
typedef unsigned char u8;
#if __CRC_LSB_MODE__
unsigned short do_crc16(unsigned short crc_val,unsigned char *message, unsigned int len)
{
unsigned int i, j;
unsigned short crc_reg =crc_val;
unsigned short current = 0;
for (i = 0; i < len; i++)
{
current = message[i];
for (j = 0; j < 8; j++)
{
if ((crc_reg ^ current) & 0x0001)
crc_reg = (crc_reg >> 1) ^ 0x8408;
else
crc_reg >>= 1;
current >>= 1;
}
}
return crc_reg;
}
#else
unsigned short do_crc16(unsigned short crc_val,unsigned char *message, unsigned int len)
{
unsigned int i, j;
unsigned short crc_reg = crc_val;
unsigned short current = 0;
for (i = 0; i < len; i++)
{
current = message[i] << 8;
for (j = 0; j < 8; j++)
{
if ((short)(crc_reg ^ current) < 0)
crc_reg = (crc_reg << 1) ^ 0x1021;
else
crc_reg <<= 1;
current <<= 1;
}
}
return crc_reg;
}
#define __CRC_TEST_MODULE__ 0
#if 0 //__CRC_TEST_MODULE__
/*
CRC-CCITT: 0x1021 = x16 + x12 + x5 + 1
Initial value: 0000
Final XOR Value: 0
input data:123456789
00 01 00 0b 31 32 33 34 35 36 37 38 39 31 c3
*/
/*
测试代码
*/
int main(int argc,char*argv[])
{
uint8_t databuff[378];
u32 i=0,file_len=0;
u16 crc_val=0;
int len=0,fd=0;
if(argc<2||argv[1]==NULL)
{
printf("check_crc [file]\n");
exit(1);
}
fd=open(argv[1],O_RDWR);
if(fd<0)
{
perror("open error");
exit(1);
}
file_len = getfilesize(fd);
for(i=0;file_len;i++)
{
len=read(fd,databuff,sizeof(databuff));
if(len<=0)
break;
file_len -=len;
crc_val=do_crc(crc_val,databuff,len);
}
printf("crc=[0x%04x] %s\n",crc_val,argv[1]);
return 0;
}
#endif
/*返回文件的大小*/
u32 get_file_size(int fd)
{
struct stat statbuf;
fstat(fd, &statbuf);
return statbuf.st_size;
}
/*返回文件的crc16值*/
unsigned short file_crc16(char * path)
{
uint8_t databuff[256];
u32 i=0,file_len=0;
u16 crc_val=0;
int len=0,fd=0;
fd=open(path,O_RDONLY);
if(fd<0)
{
return 0;
}
file_len = get_file_size(fd);
for(i=0;file_len;i++)
{
len=read(fd,databuff,sizeof(databuff));
if(len<=0)
break;
file_len -=len;
crc_val=do_crc16(crc_val,databuff,len);
}
close(fd);
return crc_val;
}
#endif