Hamming code Implementation in C / C ++ | C ++ program for the above approach ; Function to generate hamming code ; Stores the Hamming Code ; Find positions of redundant bits ; Placing - 1 at redundant bits place to identify it later ; Iterate to update the code ; Placing msgBits where - 1 is absent i . e . , except redundant bits all positions are msgBits ; If current bit is not redundant bit then continue ; Find msg bits containing set bit at x 'th position ; Generating hamming code for even parity ; Return the generated code ; Function to find the hamming code of the given message bit msgBit [ ] ; Message bit size ; r is the number of redundant bits ; Find no . of redundant bits ; Generating Code ; Print the code ; Driver Code ; Given message bits ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > generateHammingCode ( vector < int > msgBits , int m , int r ) { vector < int > hammingCode ( r + m ) ; for ( int i = 0 ; i < r ; ++ i ) { hammingCode [ pow ( 2 , i ) - 1 ] = -1 ; } int j = 0 ; for ( int i = 0 ; i < ( r + m ) ; i ++ ) { if ( hammingCode [ i ] != -1 ) { hammingCode [ i ] = msgBits [ j ] ; j ++ ; } } for ( int i = 0 ; i < ( r + m ) ; i ++ ) { if ( hammingCode [ i ] != -1 ) continue ; int x = log2 ( i + 1 ) ; int one_count = 0 ; for ( int j = i + 2 ; j <= ( r + m ) ; ++ j ) { if ( j & ( 1 << x ) ) { if ( hammingCode [ j - 1 ] == 1 ) { one_count ++ ; } } } if ( one_count % 2 == 0 ) { hammingCode [ i ] = 0 ; } else { hammingCode [ i ] = 1 ; } } return hammingCode ; } void findHammingCode ( vector < int > & msgBit ) { int m = msgBit . size ( ) ; int r = 1 ; while ( pow ( 2 , r ) < ( m + r + 1 ) ) { r ++ ; } vector < int > ans = generateHammingCode ( msgBit , m , r ) ; cout << " Message ▁ bits ▁ are : ▁ " ; for ( int i = 0 ; i < msgBit . size ( ) ; i ++ ) cout << msgBit [ i ] << " ▁ " ; cout << " Hamming code is : " ; for ( int i = 0 ; i < ans . size ( ) ; i ++ ) cout << ans [ i ] << " ▁ " ; } int main ( ) { vector < int > msgBit = { 0 , 1 , 0 , 1 } ; findHammingCode ( msgBit ) ; return 0 ; }