Cyclic Redundancy Check and Modulo | Returns XOR of ' a ' and ' b ' ( both of same length ) ; Initialize result ; Traverse all bits , if bits are same , then XOR is 0 , else 1 ; Performs Modulo - 2 division ; Number of bits to be XORed at a time . ; Slicing the divident to appropriate length for particular step ; Replace the divident by the result of XOR and pull 1 bit down ; If leftmost bit is '0' . If the leftmost bit of the dividend ( or the part used in each step ) is 0 , the step cannot use the regular divisor ; we need to use an all - 0 s divisor . ; Increment pick to move further ; For the last n bits , we have to carry it out normally as increased value of pick will cause Index Out of Bounds . ; Function used at the sender side to encode data by appending remainder of modular division at the end of data . ; Appends n - 1 zeroes at end of data ; Append remainder in the original data ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string xor1 ( string a , string b ) { string result = " " ; int n = b . length ( ) ; for ( int i = 1 ; i < n ; i ++ ) { if ( a [ i ] == b [ i ] ) result += "0" ; else result += "1" ; } return result ; } string mod2div ( string divident , string divisor ) { int pick = divisor . length ( ) ; string tmp = divident . substr ( 0 , pick ) ; int n = divident . length ( ) ; while ( pick < n ) { if ( tmp [ 0 ] == '1' ) tmp = xor1 ( divisor , tmp ) + divident [ pick ] ; else tmp = xor1 ( std :: string ( pick , '0' ) , tmp ) + divident [ pick ] ; pick += 1 ; } if ( tmp [ 0 ] == '1' ) tmp = xor1 ( divisor , tmp ) ; else tmp = xor1 ( std :: string ( pick , '0' ) , tmp ) ; return tmp ; } void encodeData ( string data , string key ) { int l_key = key . length ( ) ; string appended_data = ( data + std :: string ( l_key - 1 , '0' ) ) ; string remainder = mod2div ( appended_data , key ) ; string codeword = data + remainder ; cout << " Remainder ▁ : ▁ " << remainder << " STRNEWLINE " ; cout << " Encoded ▁ Data ▁ ( Data ▁ + ▁ Remainder ) ▁ : " << codeword << " STRNEWLINE " ; } int main ( ) { string data = "100100" ; string key = "1101" ; encodeData ( data , key ) ; return 0 ; }