近期研究RDS传输,需要进行CRC10的校验,了解crc的原理,参考其他的crc代码,实现crc10的程序。
这里准备两个函数实现crc10 和 cr10,其中cr10循环次数少一些,效率会高一些。编译的环境是Dev-C++
#include <stdio.h>
#include <stdlib.h>
#define DATA_SIZE 16
#define CRC_SIZE 10
int PATTERN = 0x1B9; //g(x)=x10+x8+x7+x5+x4+x3+1
int crc10(int dat) {
int remainder = 0;
int nremainder = 0;
int j,k;
int bit,lb;
int fb,cb;
for (j = DATA_SIZE - 1; j >= 0; j--) {
bit = (dat & (1 << j)) > 0;
lb = (remainder & (1 << (CRC_SIZE - 1))) > 0;
fb = lb ^ bit;
nremainder = fb;
for (k = 1; k < CRC_SIZE; k++) {
cb = (remainder & (1 << (k - 1))) >> k - 1;
if (PATTERN & (1 << k)) {
nremainder |= (cb ^ fb) << k;
} else {
nremainder |= cb << k;
}
}
remainder = nremainder;
}
return remainder;
}
#define POLY 0X1B9
int cr10(int dat) {
int wCRCin = 0;
int wCPoly = POLY << 16;
int i;
wCRCin ^= (dat << 10);
for(i = 0;i < DATA_SIZE;i++)
{
if(wCRCin & 0x2000000)
{
wCRCin = (wCRCin << 1) ^ wCPoly;
}
else
wCRCin = wCRCin << 1;
}
wCRCin = (wCRCin >> 16) & 0x3ff;
return (wCRCin) ;
}
int main(int argc, char *argv[]) {
printf("crc10:: data=0x0001, crc=0x%.3X\n",crc10(0x0001));
printf("crc10:: data=0xffff, crc=0x%.3X\n",crc10(0xffff));
printf("crc10:: data=0xf3ff, crc=0x%.3X\n",crc10(0xf3ff));
printf("cr10 :: data=0x0001, crc=0x%.3X\n", cr10(0x0001));
printf("cr10 :: data=0xffff, crc=0x%.3X\n", cr10(0xffff));
printf("cr10 :: data=0xf3ff, crc=0x%.3X\n", cr10(0xf3ff));
return 0;
}