2013-02-11 60 views
0
#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); 
    } 
    } 
} 

我使用的維基百科( '漢明碼(7,4)')供給的線性代數定義。在程序中的幾個點上,我打印了變量內容,但是修復了一個問題。爲了驗證輸出是否正確,我將其與維基百科上的示例進行了比較,並將結果與​​online calculator產生的結果進行了比較。漢明碼(7,4) - C++實現故障

更新:問題已解決。我使用了提供的算法here(無AMP)的改編。

+0

你是在用咬合還是用0和1的字符串做這個?我問的原因是你正在使用getline來讀取ASCII格式的字符串。你可能想從stdin中讀取fread。另外,如果你正在使用位,你可能想看看std :: bitset 來處理你的位。 – Freddy 2013-02-11 20:05:19

+0

將輸入解釋爲一個字符串,然後將每個字符轉換爲一個整數,或者爲零或一個 - 這由get_bin_representation()函數完成。 – user2062542 2013-02-11 20:10:32

回答

2

那麼,這是錯誤的:

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

漢明碼使用GF(2)算術定義。 GF(2)中的添加是C++ xor運算符(^)。使用正確的操作符,您可以取消後面的%2循環。

您還將奇偶校驗位與明文混合在一起,這在我瞭解它時從未完成過。此外,在線模擬器使用簡單的順序(明文,奇偶校驗)而不交織。