1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
| // CRC算法的C语言实现 #include<stdio.h>
// 获取字符数组长度 int len(char x[]){ int i=0; while(x[i]!='\0'){ i++; } return i; }
// 补全data void dataSet(char data[], int len_poly, char remainder[]){ int i, len_data; len_data=len(data); if(remainder[0]=='\0'){ for(i=len_data; i<len_data+len_poly-1; i++){ data[i]='0'; } }else{ for(i=len_data-len_poly+1; i<len_data+1; i++){ data[i]=remainder[i-len_data+len_poly-1]; } } }
// remainder计算 void crc(char data[], char poly[], char remainder[], int len_data, int len_poly){ char tmp[100]={'\0'}; int i,j; // 因为传参数组会对原数据进行修改(相当于传址) for(i=0;i<len_data;i++){ tmp[i]=data[i]; } for(i=0;i<len_data-len_poly;i++){ if(tmp[i]!='0'){ for(j=i;j<i+len_poly;j++){ tmp[j]=(tmp[j]-48) ^ (poly[j-i]-48)+48; } } else if(tmp[i+1]!='0'){ for(j=i+1;j<i+1+len_poly;j++) { tmp[j]=(tmp[j]-48) ^ (poly[j-1-i]-48)+48; } } } for(i=0;i<len_poly;i++){ remainder[i]=tmp[len_data-len_poly+1+i]; } }
// 测试CRC void crcTest(char remainder[]){ int i; for(i=0;i<len(remainder);i++){ if(remainder[i]!='0'){ printf("False\n"); return; } } printf("True\n"); }
int main(){ char data[100]={'0'}; char polynomial[10]={'\0'}; char remainder[10]={'\0'}; scanf("%s",data); //11010011101100 scanf("%s",polynomial); // 10011 printf("%d %d\n",len(data),len(polynomial)); printf("Data is %s\n",data);
dataSet(data,len(polynomial),remainder); crc(data, polynomial, remainder, len(data),len(polynomial)); printf("Remainder is %s\n",remainder); //1011
dataSet(data,len(polynomial),remainder); printf("CRC is %s\n",data); //110100111011001011 crc(data, polynomial, remainder, len(data),len(polynomial)); crcTest(remainder); //True return 0; }
|