[英]How to implement modulo-2 binary division in c++
现在我想在 c++ 中实现循环冗余检查,所以我想知道如何执行 mod 2 二进制除法。
好吧,虽然我知道 mod-2 二进制 div 有一个字符串算法,但我想知道是否有任何 int 算法。 对不起我的菜鸟解释。
谢谢你。
模 2 除法使用异或运算而不是减法,下面是 c++ 的实现
#include <iostream>
#include <math.h>
#include <cstring>
using namespace std;
char exor(char a,char b) // perform exor operation
{
if(a==b)
return '0';
else
return '1';
}
void modulo2div(char data[], char key[], int datalen, int keylen)
{
char temp[20],rem[20];
for(int i=0;i<keylen;i++)
rem[i]=data[i]; //considering keylen-1 bits of data for each step of binary division/EXOR
for(int j=keylen;j<=datalen;j++)
{
for(int i=0;i<keylen;i++)
temp[i]=rem[i]; // remainder of previous step is divident of current step
if(rem[0]=='0') //if 1's bit of remainder is 0 then shift the rem by 1 bit
{
for(int i=0;i<keylen-1;i++)
rem[i]=temp[i+1];
}
else //else exor the divident with generator polynomial
{
for(int i=0;i<keylen-1;i++)
rem[i]=exor(temp[i+1],key[i+1]);
}
rem[keylen-1]=data[j]; //appending next bit of data to remainder obtain by division
}
cout<<"CRC="<<rem<<"\nDataword="<<data; //remainder obtain is crc
}
有关详细信息,请访问C++ 中的 CRC 实现
#include <iostream>
using namespace std;
int main(){
int bits[100],generator[20];
int sizebits , sizeGen ;
cin >> sizebits >> sizeGen ;
for(int i = 0; i < sizebits ; i++)
cin >> bits[i];
for(int i = 0; i < sizeGen ; i++)
cin >> generator[i];
for(int i = 0; i < sizebits-sizeGen;){
for(int j = 0; j < sizeGen; j++)
bits[i+j] = (bits[i+j] == generator[j]? 0 : 1) ;
for(; i < sizebits-sizeGen && bits[i] != 1 ;i++);
}
for(int i = 0; i < sizebits ; i++)
cout << bits[i];
return 0;
}
可以这样做!
这是 CRC 的代码示例,使用 Modulo-2 二进制除法):
/*
* The width of the CRC calculation and result.
* Modify the typedef for a 16 or 32-bit CRC standard.
*/
typedef uint8_t crc;
#define WIDTH (8 * sizeof(crc))
#define TOPBIT (1 << (WIDTH - 1))
crc
crcSlow(uint8_t const message[], int nBytes)
{
crc remainder = 0;
/*
* Perform modulo-2 division, a byte at a time.
*/
for (int byte = 0; byte < nBytes; ++byte)
{
/*
* Bring the next byte into the remainder.
*/
remainder ^= (message[byte] << (WIDTH - 8));
/*
* Perform modulo-2 division, a bit at a time.
*/
for (uint8_t bit = 8; bit > 0; --bit)
{
/*
* Try to divide the current data bit.
*/
if (remainder & TOPBIT)
{
remainder = (remainder << 1) ^ POLYNOMIAL;
}
else
{
remainder = (remainder << 1);
}
}
}
/*
* The final remainder is the CRC result.
*/
return (remainder);
} /* crcSlow() */
来自https://barrgroup.com/Embedded-Systems/How-To/CRC-Calculation-C-Code 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.