Hamming Code (7,4) - C++ Implementation Failure

user2062542 picture user2062542 · Feb 11, 2013 · Viewed 7.9k times · Source
#include <iostream>
#include <string>

using namespace std;

int get_bin_representation(char x){

  if(x == '1'){
    return 1;
  }
  else if(x == '0'){
    return 0;
  }
}
int gen_hamming_code(string token){

  int bits[4];
  int temp(0);

  for(int k=0; k<4; k++){
    bits[k] = get_bin_representation(token.at(k));
  }

  int ham_code[7];

  ham_code[0] = bits[0] + bits[1] + bits[3];
  ham_code[1] = bits[0] + bits[2] + bits[3];
  ham_code[2] = bits[0];
  ham_code[3] = bits[1] + bits[2] + bits[3];
  ham_code[4] = bits[1];
  ham_code[5] = bits[2];
  ham_code[6] = bits[3];

  for(int h=0; h<7; h++){
    temp = ham_code[h];
    ham_code[h] = temp%2;
    temp = 0;
  }

  for(int e=0; e<7; e++){
    cout << ham_code[e];
  }
  cout << endl;

  return 0;
}
int main(){

  string usr_input;
  string msg;
  int index(0);

  cout << "Hamming Code Program" << endl;

  while(true){

    cout << endl << ": ";
    getline(cin, usr_input);

    if(usr_input.find("gen") != std::string::npos){
        for(int i=0; i<usr_input.length(); i++){
            if(usr_input.at(i) == ' '){
                index = i;
            }
        }

        for(int j=index; j<usr_input.length(); j++){
            msg+=usr_input.at(j);
        }

        cout << "Hamming code (7,4): ";
        gen_hamming_code(msg);
    }
  }
}

I used the linear algebra definition supplied by Wikipedia ('Hamming Code (7,4)'). At several points in the program, I printed the variable contents, but fixing one problem lead to another. To verify if the output was correct, I compared it to the example available on Wikipedia, and the result produced by an online calculator.

UPDATED: Question resolved. I used an adaptation of the algorithm provided here (without AMP).

Answer

Ben Voigt picture Ben Voigt · Feb 11, 2013

Well, this is wrong:

ham_code[0] = bits[0] + bits[1] + bits[3];

Hamming codes are defined using GF(2) arithmetic. Addition in GF(2) is the C++ xor operator (^). Use the right operator, and you can do away with the later %2 loop.

You've also intermingled the parity bits with the plaintext, which is something never done when I learned about it. As well, the online simulator is using the simple order (plaintext, parity) without interleaving.