-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCRC.cpp
93 lines (92 loc) · 2.31 KB
/
CRC.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#include <bits/stdc++.h>
using namespace std;
string xor1(string a, string b)
{
string result = "";
int n = b.length();
for (int i = 1; i < n; i++)
{
if (a[i] == b[i])
result += "0";
else
result += "1";
}
return result;
}
string mod2div(string dividend, string divisor)
{
int pick = divisor.length();
string tmp = dividend.substr(0, pick);
int n = dividend.length();
while (pick < n)
{
if (tmp[0] == '1')
tmp = xor1(divisor, tmp) + dividend[pick];
else
tmp = xor1(std::string(pick, '0'), tmp) + dividend[pick];
pick += 1;
}
if (tmp[0] == '1')
tmp = xor1(divisor, tmp);
else
tmp = xor1(std::string(pick, '0'), tmp);
return tmp;
}
void encodeData(string data, string key)
{
int l_key = key.length();
string appended_data = (data + std::string(l_key - 1, '0'));
string remainder = mod2div(appended_data, key);
string codeword = data + remainder;
cout << "Remainder : " << remainder << "\n";
cout << "Encoded Data (Data + Remainder) :" << codeword << "\n";
}
void receiver(string data, string key)
{
string currxor = mod2div(data.substr(0, key.size()), key);
int curr = key.size();
while (curr != data.size())
{
if (currxor.size() != key.size())
{
currxor.push_back(data[curr++]);
}
else
{
currxor = mod2div(currxor, key);
}
}
if (currxor.size() == key.size())
{
currxor = mod2div(currxor, key);
}
if (currxor.find('1') != string::npos)
{
cout << "there is some error in data" << endl;
}
else
{
cout << "correct message received" << endl;
}
}
int main()
{
string data;
string generator;
int frameSize, generatorSize;
cout << "Enter the frame size: " << endl;
cin >> frameSize;
cout << "Enter the generator size: " << endl;
cin >> generatorSize;
cout << "Enter the data:";
cin >> data;
cout << "Enter the generator:";
cin >> generator;
cout << "\nSender side..." << endl;
encodeData(data, generator);
cout << "\nReceiver side..." << endl;
receiver(
data + mod2div(data + std::string(generator.size() - 1, '0'), generator),
generator);
return 0;
}