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和1的字符串做這個?我問的原因是你正在使用getline來讀取ASCII格式的字符串。你可能想從stdin中讀取fread。另外,如果你正在使用位,你可能想看看std :: bitset來處理你的位。 –
Freddy
2013-02-11 20:05:19
將輸入解釋爲一個字符串,然後將每個字符轉換爲一個整數,或者爲零或一個 - 這由get_bin_representation()函數完成。 – user2062542 2013-02-11 20:10:32