-
Notifications
You must be signed in to change notification settings - Fork 0
/
crcCode.cpp
85 lines (73 loc) · 2.01 KB
/
crcCode.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
#include <bits/stdc++.h>
using namespace std;
string xor1(string a, string b)
{
string result = "";
int n = b.length();
// traverse all bits if bits are same return 0 , if diffrent return 1.
for (int i = 1; i < n; i++)
{
if (a[i] == b[i])
{
result += '0';
}
else
{
result += '1';
}
}
return result;
}
string mod2div(string divident, string divisor)
{
int pick = divisor.length();
// slicing the divident according to the length of pick.
string tmp = divident.substr(0, pick);
int n = divident.length();
while (pick < n)
{
if (tmp[0] == '1')
{
tmp = xor1(divisor, tmp) + divident[pick]; // divident[pick] = pulling bit down
}
else
{
// if leftmost bit = '0' we wont procees it thus will move to so that leftmost bit is 1.
tmp = xor1(std::string(pick, '0'), tmp) + divident[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();
// appending n-1 zero at end since if key length = n , zeros appended = n-1
string appended_data = (data + std::string(l_key - 1, '0'));
// cout << appended_data << " ";
string remainder = mod2div(appended_data, key);
reverse(remainder.begin(), remainder.end());
// append remainder in orginal data
string codeword = data + remainder;
cout << "Remainder : " << remainder << "\n";
cout << "Encoded Data (Data + Remainder) :" << codeword << "\n";
}
int main()
{
string data = "100100";
string key = "1101";
// string data = "10011101";
// string key = "1001";
// string data;
// cout << "Enter string data: " << endl;
// cin >> data;
// string key;
// cout << " Enter string key: " << endl;
// cin >> key;
encodeData(data, key);
return 0;
}