Hamming code Implementation in C/C++

• Difficulty Level : Hard
• Last Updated : 26 Jul, 2021

Pre-requisite: Hamming Code

Given a message bit in the form of an array msgBit[], the task is to find the Hamming Code of the given message bit.

Examples:

Input: S = “0101”
Output:
Generated codeword:
r1 r2 m1 r4 m2 m3 m4
0  1   0    0  1     0    1
Explanation:
Initially r1, r2, r4 is set to ‘0’.
r1 = Bitwise XOR of all bits position that has ‘1’ in its 0th-bit position.
r2 = Bitwise XOR of all bits that has ‘1’ in its 1st-bit position.
r3 = Bitwise XOR of all bits that has ‘1’ in its 2nd-bit position.

Input: S  = “0111”
Output:
Generated codeword:
r1 r2 m1 r4 m2 m3 m4
0  0   0    1  1     1    1

Approach: The idea is to first find the number of redundant bits which can be found by initializing r with 1 and then incrementing it by 1 each time while 2r is smaller than (m + r + 1) where m is the number of bits in the input message. Follow the below steps to solve the problem:

• Initialize r by 1 and increment it by 1 until 2r is smaller than m+r+1.
• Initialize a vector hammingCode of size r + m which will be the length of the output message.
• Initialize all the positions of redundant bits with -1 by traversing from i = 0 to r – 1 and setting hammingCode [2i 1] = -1. Then place the input message bits in all the positions where hammingCode[j] is not -1 in order where 0 <= j < (r + m).
• Initialize a variable one_count with 0 to store the number of ones and then traverse from i = 0 to (r + m – 1).
• If the current bit i.e., hammingCode[i] is not -1 then find the message bit containing set bit at log2(i+1)th position by traversing from j = i+2 to r+m by incrementing one_count by 1 if (j & (1<<x)) is not 0 and hammingCode[j – 1] is 1.
• If for index i, one_count is even, set hammingCode[i] = 0 otherwise set hammingCode[i] = 1.
• After traversing, print the hammingCode[] vector as the output message.

Below is the implementation of the above approach:

C

 // C program for the above approach #include #include  // Store input bitsint input; // Store hamming codeint code; int ham_calc(int, int);void solve(int input[], int); // Function to calculate bit for// ith positionint ham_calc(int position, int c_l){    int count = 0, i, j;    i = position - 1;     // Traverse to store Hamming Code    while (i < c_l) {         for (j = i; j < i + position; j++) {             // If current boit is 1            if (code[j] == 1)                count++;        }         // Update i        i = i + 2 * position;    }     if (count % 2 == 0)        return 0;    else        return 1;} // Function to calculate hamming codevoid solve(int input[], int n){    int i, p_n = 0, c_l, j, k;    i = 0;     // Find msg bits having set bit    // at x'th position of number    while (n > (int)pow(2, i) - (i + 1)) {        p_n++;        i++;    }     c_l = p_n + n;     j = k = 0;     // Traverse the msgBits    for (i = 0; i < c_l; i++) {         // Update the code        if (i == ((int)pow(2, k) - 1)) {            code[i] = 0;            k++;        }         // Update the code[i] to the        // input character at index j        else {            code[i] = input[j];            j++;        }    }     // Traverse and update the    // hamming code    for (i = 0; i < p_n; i++) {         // Find current position        int position = (int)pow(2, i);         // Find value at current position        int value = ham_calc(position, c_l);         // Update the code        code[position - 1] = value;    }     // Print the Hamming Code    printf("\nThe generated Code Word is: ");    for (i = 0; i < c_l; i++) {        printf("%d", code[i]);    }} // Driver Codevoid main(){    // Given input message Bit    input = 0;    input = 1;    input = 1;    input = 1;     int N = 4;     // Function Call    solve(input, N);}

C++

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

Time Complexity: O((M + R)2) where M is the number of bits in the input message and R is the number of redundant bits
Auxiliary Space: O(M + R)

My Personal Notes arrow_drop_up