#include<iostream>
#include <stdio.h>
#include <string>
#include <stdlib.h>
using namespace std;
string generator(string message, string G);//循环冗余算法
void verifier(string message, string G);//用生成多项式判断接收信息是否正确
string modtwo(string message, string G);//除模算法实现
void alter(int num,string& message,string G)//制造某个比特位传输错误的传输现象
string generator(string message, string G)
{
for (int i = 1; i < size(G); i++)//补零
{
message = message + '0';
}
cout << "加上零之后的message是:" << message << endl;
string temp = modtwo(message, G);
cout << "计算出来的模是:" << temp << endl;
for (int i =0; i<temp.size();i++)
{
message[message.size()+i-temp.size()] = temp[i];
}
cout << "最后传输的message变成了:" << message << endl;
return message;
}
string modtwo(string message,string G)
{
string temp;
string a = message;
if (a.size() < G.size())
{
bool flag= 0;
for (int j = 0; j < a.size(); j++)
{
if (a[j] != '0')
{
flag = 1;
}
}
if (flag == 0)
{
return "0";
}
while (a[0] == 0)
{
a.erase(0, 1);
}
return a;
}
else
{
for (int i = 0; i < G.size(); i++)
{
if (G[i] != a[i])
{
temp = temp + '1';
}
else
{
temp = temp + '0';
}
}
while (temp[0] == '0')
{
temp.erase(0, 1);
}
for (int i = G.size(); i < a.size(); i++)
{
temp = temp + a[i];
}
a = temp;
return modtwo(a, G);
}
}
void verifier(string message, string G)
{
string a = modtwo(message, G);
bool flag = 0;
for (int i = 0; i < a.size(); i++)
{
if (a[i] != '0')
{
flag = 1;
}
}
if (flag == 0)
{
cout << "信息传输无误" << endl;
}
else
{
cout << "信息传输错误" << endl;
}
}
void alter(int num,string& message,string G)
{
if (message[num + 1] == '0')
{
message[num + 1] = '1';
}
else
{
message[num + 1] = '0';
}
cout << "再判断接受信息的正误:";
verifier(message, G);
}
int main()
{
string message, G;
int x;
cout << "请输入待传输信息:";
getline(cin, message);
cout << "请输入生成多项式:";
getline(cin, G);
message=generator(message, G);
verifier(message, G);
cout << "传输过程使得信息中出现错误的比特位是:" << endl;
cin >> x;
alter(x, message,G);
return 0;
}