-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparityCheckError.cpp
More file actions
46 lines (43 loc) · 1.25 KB
/
parityCheckError.cpp
File metadata and controls
46 lines (43 loc) · 1.25 KB
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
#include <bits/stdc++.h>
#include <ctime>
using namespace std;
int main()
{
srand(time(0));
string data = "1111010011";
cout << "\nOriginal data to be sent: " << data;
int numberOfOnes = 0;
for (int i = 0; i < data.size(); i++)
{
if (data[i] == '1')
numberOfOnes++;
}
string encryptedData = data + (numberOfOnes % 2 == 0 ? '0' : '1');
cout << "\nAppending the parity bit with the data (data + parity bit): " << encryptedData;
//make a random change in the encrypted data due to noise:
cout << "\nSimulating a probable noise... ";
int ifNoiseOccured = rand() % 2;
if (ifNoiseOccured == 1)
{
int randomIndex = rand() % data.size();
cout << "\nNoise occured at position " << randomIndex << "!";
encryptedData[randomIndex] = encryptedData[randomIndex] == '1' ? '0' : '1';
}
else
{
cout << "\nNo noise occured!";
}
cout << "\nChecking the received message for an error...";
numberOfOnes = 0;
int parityBit = encryptedData[encryptedData.size() - 1] == '1' ? 1 : 0;
for (int i = 0; i < encryptedData.size() - 1; i++)
{
if (encryptedData[i] == '1')
numberOfOnes++;
}
if (numberOfOnes % 2 == parityBit)
cout << "\nNo error was detected!";
else
cout << "\nAn error was detected!";
return 0;
}