Cyclic Redundancy Check CRC program in C++

 

What is Cyclic Redundancy Check?

Cyclic Redundancy Check CRC is an error detection algorithm used in communication networks to check if the transmitted data contains any error.

How CRC works?

CRC generator at sender's end:

1. CRC used a n bit generator polynomial which works as divisor.

    Generator = 10101  then n=5

2. Append n-1 number of zeros to the data word.

     Data word = 110010101

     Appended data word = 110010101 + 0000 = 1100101010000

3. Divide the appended data word by the generator by using binary division.

        

Cyclic Redundancy Check CRC program in C++

 

4. The remainder obtained after division is a n-1 bit CRC code.

Remainder = n-1 bit CRC code =1011

5. Replace the n-1 zeros in data word with the n-1 bit CRC code.

Final data word = 110010101 + 1011 = 1100101011011

6. Transmit the CRC appended data word.

CRC checker at receiver's end:

1. Divide the received data word by the same generator.

2. If the remainder is zero than data is not erroneous else it contains error.

 

CRC implementation in 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 crc(char data[], char key[])
{
int datalen = strlen(data);
int keylen = strlen(key);

for(int i=0;i<keylen-1;i++)                //appending n-1 zeroes to data
data[datalen+i]='0';
data[datalen+keylen-1]='\0';

int codelen = datalen+keylen-1;                //lenght of appended data word

char temp[20],rem[20];

for(int i=0;i<keylen;i++)
rem[i]=data[i];                    //considering n bits of data for each step of binary division/EXOR

for(int j=keylen;j<=codelen;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 key
    {   
        for(int i=0;i<keylen-1;i++)
            rem[i]=exor(temp[i+1],key[i+1]);
           
    }
    if(j!=codelen)
        rem[keylen-1]=data[j];        //appending next bit of data to remainder obtain by division
    else
        rem[keylen-1]='\0';
}
    
for(int i=0;i<keylen-1;i++)
data[datalen+i]=rem[i];                //replace n-1 zeros with n-1 bit CRC
data[codelen]='\0';
cout<<"CRC="<<rem<<"\nDataword="<<data;

}

int main()
{
char key[20],data[20];

cout<<"Enter the data:";
cin>>data;
cout<<"Enter the key:";
cin>>key;

crc(data,key);                        // generate crc

return 0;
}

Output :

Cyclic Redundancy Check CRC program in C++


Comments