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