📄 gen_crc16_table.c
字号:
#include <stdio.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#define CRC16POLY 0x8005
#define CRC16POLY_REV 0xa001
#define CRC_CCITT0 0x1021
#define CRC_CCITT0_REV 0x8408
#define FCS(crcnum, c) (((crcnum) << 8) ^ crc16_table[(((crcnum) >> 8) ^ (c)) & 0xff])
#define FCS_REV(crcnum, c) (((crcnum) >> 8) ^ crc16_table[((crcnum) ^ (c)) & 0xff])
#define REVERSE 1
unsigned short crc16_table[256];
void init_crc16_table(unsigned short genpoly)
{
unsigned short ccnum = 0;
unsigned short i, j, k;
for(i=0; i<256; i++)
{
ccnum = 0;
#if REVERSE
k = (i << 1);
for(j=8;j>0;j--)
{
k >>= 1;
if((k ^ ccnum) & 0x0001)
ccnum = (ccnum >> 1) ^ genpoly;
else
ccnum >>= 1;
}
#else
k = (i << 8);
for(j=8;j>0;j--)
{
if((k^ccnum) & 0x8000)
ccnum = (ccnum <<= 1) ^ genpoly;
else
ccnum <<= 1;
k <<= 1;
}
#endif
crc16_table[i] = ccnum;
}
}
unsigned short Trid_CRC16_Gen(unsigned char *buf, int len)
{
unsigned short oldcrc16;
unsigned short crc16;
unsigned short oldcrc;
unsigned int charcnt;
char c, t;
//oldcrc16 = 0x0000; //初值为0
crc16 = 0xffff;
//crc16 = 0x0000;
charcnt = 0;
/*
while(len--)
{
t = (oldcrc16 >> 8) & 0xFF; //要移出的字节的值
//oldcrc = crc16_table[t]; //根据移出的字节的值查表
c = buf[charcnt]; //新移进来的字节值
oldcrc16 <<= 8;
//printf("\n0x%x\n", t ^ c);
//printf("\n0x%x\n", oldcrc16);
oldcrc16 ^= crc16_table[(t ^ c) & 0xff];
charcnt++;
}
crc16 = oldcrc16;
*/
while(len--)
{
c = buf[charcnt++];
#if REVERSE
crc16 = FCS_REV(crc16, c);
#else
crc16 = FCS(crc16, c);
#endif
}
return ~crc16;
}
void main()
{
int i;
unsigned char data = 0x10;
unsigned char j=0;
//int fd;
//fd = open("table.txt", O_CREAT | O_RDWR);
//if(fd == -1)
//{
// printf("open file error!!\n");
// exit(-1);
//}
FILE *fp;
fp = fopen("table.txt", "w+");
if(fp == NULL)
{
printf("error\n");
exit(-1);
}
init_crc16_table(CRC_CCITT0_REV);
for(i=0; i<256; i++)
{
//fprintf(fp, "0x%x, ", crc16_table[i]);
printf("0x%04x ", crc16_table[i]);
if((i % 8) == 7)
//fprintf(fp, "\n");
printf("\n");
}
printf("\n\n0x%04x\n\n", Trid_CRC16_Gen(&data, 1));
for(i=0; i<256; i++)
{
printf("0x%04x ", Trid_CRC16_Gen(&j, 1));
if((i%8) == 7)
printf("\n");
j++;
}
fclose(fp);
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -