Last active
December 19, 2015 09:29
-
-
Save motpro/5933344 to your computer and use it in GitHub Desktop.
hht速来膜拜
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| CRC检验码计算 | |
| 1.需求分析 | |
| CRC 中文名叫循环冗余校验,这个给技术是数据通讯领域中最常用的一种差错校验码,特点是校验字符串跟信息都可以自定。课题要求是编程实现CRC,并且校验数据的正确性。 | |
| CRC的基本原理是在第K位信息码后面再接R位的校验码,整个信息的长度为N为,所以又可以叫做(N,K)码。对于给定的CRC信息码,可以证明证明存在一个最高次幂为N-K的多项式G(x)。根据G(x)可以生成K位的信息的校验码,G(x)叫做这个CRC信息码的生成多项式。 | |
| 校验码的具体生成过程是:假设原信息用多项式表示,讲C(x)左移R位,则可以表示成C(x)*2的R次方除以生成的多项式G(x),得到余数就是校验码。 | |
| 设计算法: | |
| 1.将x的最高幂次为R的多项式G(x)转换成对应的二进制数,长度为R+1位. | |
| 2.将信息码左移R位,相当于对应的信息多项式C(x)*2的R次方. | |
| 3.用(二进制)多项式对信息码作除,得到长度为R的余数. | |
| 4.将余数接到信息码左移之后空出的位置,得到完整的CRC. | |
| 代码(c++): | |
| #include <iostream> | |
| #include <string> | |
| using std::string; | |
| string getcrc( string data,string div_num) { | |
| string s1,s2,temp; | |
| int len; | |
| len = div_num.length(); | |
| for( int i = 0 ; i < len - 1; i++) | |
| data.append("0"); | |
| while( data.length() >= div_num.length()) { | |
| s2 = ""; | |
| s1 = data.substr(0,len); | |
| data = data.substr(len,data.length()-len); | |
| for( int i = 0 ; i < div_num.length();i++){ | |
| if( s1[i] == div_num[i]) | |
| s2.append("0"); | |
| else | |
| s2.append("1"); | |
| } | |
| //去掉前面的0 | |
| while( s2.length() != 0) { | |
| temp = s2[0]; | |
| if( temp.compare("0") != 0) | |
| break; | |
| s2= s2.substr(1,s2.length()-1); | |
| } | |
| data = s2.append(data); | |
| } | |
| return data; | |
| } | |
| int main() { | |
| //demo 1101011011 / 10011 | |
| string data = "1101011011"; | |
| string div_num = "10011"; | |
| string crc = getcrc( data , div_num); | |
| std::cout<<data<<crc<<std::endl; | |
| return 0; | |
| } | |
| CRC补零: | |
| 得到crc之后,如果长度不够R 就需要把0还原操作如下 | |
| string crc_2 = ""; //还原之后的crc | |
| if(crc.length() != div_num.length()) | |
| { | |
| for( int i = 0; i < div_num.length()-crc.length()-1;i++) | |
| crc_2.append("0"); //补0 | |
| crc_2.append(crc) //加上crc | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment