0% found this document useful (0 votes)
2 views29 pages

Cnlab 1

The document outlines various error detection and correction techniques in computer networks, including Hamming Code, Cyclic Redundancy Check (CRC), 2-D Parity Check, and Checksum. Each section includes an aim, algorithm, and a corresponding C++ program that demonstrates the implementation of the technique. The programs cover data input, error introduction, and verification of the data integrity.

Uploaded by

ekanshk7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views29 pages

Cnlab 1

The document outlines various error detection and correction techniques in computer networks, including Hamming Code, Cyclic Redundancy Check (CRC), 2-D Parity Check, and Checksum. Each section includes an aim, algorithm, and a corresponding C++ program that demonstrates the implementation of the technique. The programs cover data input, error introduction, and verification of the data integrity.

Uploaded by

ekanshk7
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

COMPUTER NETWORKS LAB DA-1

23BCE0414
EKANSH KUMAR
1.HAMMING CODE:
AIM AND ALGORITHM:
PROGRAM:

#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
#include <random>

using namespace std;

random_device rd;
mt19937 gen(rd());

void printWord(const vector<int>& word) {


for (int bit : word) cout << bit;
cout << endl;
}

void printRevWord(const vector<int>& word) {


for (int i = word.size() - 1; i >= 0; --i) cout << word[i];
cout << endl;
}

int getCodewordLength(int n) {
int r = 0;
while ((1 << r) < (n + r + 1)) r++;
return n + r;
}

bool isPowerOfTwo(int n) {
return n > 0 && (n & (n - 1)) == 0;
}

int findParity(const vector<int>& codeWord, int pos, int parityType) {


int parity = (parityType == 1) ? 1 : 0;
for (int i = 1; i <= codeWord.size(); ++i) {
if (i & pos) {
parity ^= codeWord[i - 1];
}
}
return parity;
}

void generateHammingCode(vector<int>& dataWord, vector<int>&


codeWord, int parityType) {
int n = dataWord.size();
int k = codeWord.size();
int j = n - 1;

for (int i = 1; i <= k; ++i) {


if (isPowerOfTwo(i))
codeWord[i - 1] = 0;
else
codeWord[i - 1] = dataWord[j--];
}

cout << "Parity Bits:\n";


for (int i = 0; i < k - n; ++i) {
int pow = 1 << i;
int parity = findParity(codeWord, pow, parityType);
codeWord[pow - 1] = parity;
cout << "R" << pow << ": " << parity << endl;
}

cout << "Codeword: ";


printRevWord(codeWord);
cout << endl;
}

int convertToDecimal(const vector<int>& word) {


int dec = 0;
for (int i = 0; i < word.size(); ++i)
dec += word[i] * (1 << i);
return dec;
}

void verifyCodeword(vector<int>& codeWord, int r, int parityType) {


vector<int> parityWord;
cout << "Parity Bits:\n";
for (int i = 0; i < r; ++i) {
int pow = 1 << i;
int parity = findParity(codeWord, pow, parityType);
parityWord.push_back(parity);
cout << "C" << pow << ": " << parity << endl;
}

int errorPosition = convertToDecimal(parityWord);


cout << "Result of verification logic: ";

if (errorPosition == 0) {
cout << "No error detected.\n";
} else {
cout << "Error in bit position " << errorPosition << endl;
codeWord[errorPosition - 1] ^= 1;
cout << "Codeword after correction: ";
printRevWord(codeWord);
}

vector<int> data;
for (int i = 1; i <= codeWord.size(); ++i) {
if (!isPowerOfTwo(i))
data.push_back(codeWord[i - 1]);
}

cout << "Dataword: ";


printRevWord(data);
}

int main() {
int n, parityType, hasError, manual, errorBit;

cout << "\nEnter Length of Data Word: ";


cin >> n;

cout << "Input the Data Word: ";


vector<int> dataWord(n);
for (int& bit : dataWord) cin >> bit;

int codewordLength = getCodewordLength(n);


vector<int> codeWord(codewordLength, 0);

cout << "Input Parity (Odd-1 / Even-0): ";


cin >> parityType;

cout << "Enter choice (Error-1 / Errorless Transmission-0): ";


cin >> hasError;

if (hasError == 1) {
cout << "Introduce Error (Manual-1 / Random-0): ";
cin >> manual;
if (manual == 1) {
cout << "Enter Error Bit: ";
cin >> errorBit;
} else if (manual == 0) {
errorBit = uniform_int_distribution<int>(1, codewordLength)(gen);
} else {
cout << "Invalid choice\n";
return 0;
}
}

cout << "\nSender Side:\n";


cout << "Given Data Word: ";
printRevWord(dataWord);

generateHammingCode(dataWord, codeWord, parityType);

cout << "Receiver Side:\n";

if (hasError == 1) {
if (manual == 1)
cout << "Error introduced at Bit " << errorBit << " manually.\n";
else
cout << "Error introduced at Bit " << errorBit << " randomly.\n";

codeWord[errorBit - 1] ^= 1;
cout << "Received Codeword with Error: ";
printRevWord(codeWord);
} else {
cout << "No Error introduced.\n";
}

verifyCodeword(codeWord, codewordLength - n, parityType);

return 0;
}

EXECUTION:
2.CYCLIC REDUNDANCY CHECK-(CRC):
AIM AND ALGORITHM:
PROGRAM:

#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;

string xorStrings(string a, string b) {


string result = "";
for (int i = 1; i < b.length(); i++)
result += (a[i] == b[i]) ? '0' : '1';
return result;
}

string mod2div(string dividend, string divisor) {


int pick = divisor.length();
string temp = dividend.substr(0, pick);
while (pick < dividend.length()) {
if (temp[0] == '1')
temp = xorStrings(divisor, temp) + dividend[pick];
else
temp = xorStrings(string(pick, '0'), temp) + dividend[pick];
pick++;
}
if (temp[0] == '1')
temp = xorStrings(divisor, temp);
else
temp = xorStrings(string(pick, '0'), temp);
return temp;
}
string generateCodeword(string data, string key) {
string appended = data + string(key.length() - 1, '0');
string remainder = mod2div(appended, key);
return data + remainder;
}

string introduceError(string codeword, int type) {


string corrupted = codeword;
int len = corrupted.length();

if (type == 1) {
int pos = rand() % len;
corrupted[pos] = (corrupted[pos] == '0') ? '1' : '0';
cout << "Single-bit error introduced at position: " << pos << endl;
}
else if (type == 2) {
int count = 3;
cout << "Introducing " << count << " random bit flips (odd)\n";
for (int i = 0; i < count; i++) {
int pos = rand() % len;
corrupted[pos] = (corrupted[pos] == '0') ? '1' : '0';
}
}
else if (type == 3) {
int burstLen = 5;
int start = rand() % (len - burstLen);
cout << "Burst error introduced from position " << start
<< " to " << start + burstLen - 1 << endl;
for (int i = 0; i < burstLen; i++) {
corrupted[start + i] = (corrupted[start + i] == '0') ? '1' : '0';
}
}
return corrupted;
}

int main() {
srand(time(0));
string data, key;

cout << "Input 16-bit dataword: ";


cin >> data;
if (data.size() != 16) {
cout << "Invalid input. Dataword must be 16 bits.\n";
return 1;
}

cout << "Input generator polynomial (e.g., 100000111): ";


cin >> key;
if (key.size() < 3) {
cout << "Invalid polynomial. Try again.\n";
return 1;
}
string codeword = generateCodeword(data, key);
cout << "\nSender Side:\nDataword: " << data << "\nGenerator
Polynomial: " << key
<< "\nCodeword (Data + CRC bits): " << codeword << endl;

cout << "\nTransmission Mode (0: Errorless | 1: Single-bit error | 2: Odd-


bit error | 3: Burst error): ";
int choice;
cin >> choice;

string received;
if (choice == 0) {
received = codeword;
cout << "No error introduced.\n";
} else {
received = introduceError(codeword, choice);
cout << "Received Codeword: " << received << endl;
}

cout << "\nReceiver Side:\nReceived Codeword: " << received << endl;
string remainder = mod2div(received, key);

if (remainder.find('1') == string::npos)
cout << "Result of verification logic: ✅ No error detected (Remainder
= 0)\n";
else
cout << "Result of verification logic: ❌ Error detected (Remainder = "
<< remainder << ")\n";

return 0;
}

EXECUTION:

3.2-D PARITY CHECK:


AIM AND ALGORITHM:
PROGRAM:
#include <iostream>
#include <vector>
#include <ctime>
#include <cstdlib>
using namespace std;

typedef vector<vector<int> > Matrix;

Matrix getDataMatrix(string data16) {


Matrix mat(4, vector<int>(4));
for (int i = 0; i < 16; i++) {
mat[i / 4][i % 4] = data16[i] - '0';
}
return mat;
}

void addParity(Matrix& mat) {


for (int i = 0; i < 4; i++) {
int rowParity = 0;
for (int j = 0; j < 4; j++) rowParity ^= mat[i][j];
mat[i].push_back(rowParity);
}

vector<int> colParity;
for (int j = 0; j < 5; j++) {
int p = 0;
for (int i = 0; i < 4; i++) p ^= mat[i][j];
colParity.push_back(p);
}
mat.push_back(colParity);
}

void printMatrix(Matrix mat, string label) {


cout << label << endl;
for (int i = 0; i < mat.size(); i++) {
for (int j = 0; j < mat[0].size(); j++)
cout << mat[i][j] << " ";
cout << endl;
}
}

Matrix simulateError(Matrix mat, int type) {


if (type == 0) return mat;

int r1, r2, r3, c1, c2, c3;


switch (type) {
case 1: // single bit error
r1 = rand() % 4;
c1 = rand() % 4;
mat[r1][c1] ^= 1;
break;
case 2: // 2-bit error in same row
r1 = rand() % 4;
c1 = rand() % 4;
do { c2 = rand() % 4; } while (c2 == c1);
mat[r1][c1] ^= 1;
mat[r1][c2] ^= 1;
break;
case 3: // three bit errors in different rows/columns
r1 = rand() % 4; c1 = rand() % 4;
r2 = (r1 + 1) % 4; c2 = (c1 + 1) % 4;
r3 = (r2 + 1) % 4; c3 = (c2 + 1) % 4;
mat[r1][c1] ^= 1;
mat[r2][c2] ^= 1;
mat[r3][c3] ^= 1;
break;
case 4: // 4-bit rectangle error
r1 = rand() % 3;
c1 = rand() % 3;
for (int i = r1; i < r1 + 2; i++)
for (int j = c1; j < c1 + 2; j++)
mat[i][j] ^= 1;
break;
}
return mat;
}

void detectError(Matrix mat) {


int rowErr = -1, colErr = -1;
for (int i = 0; i < 4; i++) {
int parity = 0;
for (int j = 0; j < 4; j++) parity ^= mat[i][j];
if (parity != mat[i][4]) {
rowErr = i;
break;
}
}
for (int j = 0; j < 4; j++) {
int parity = 0;
for (int i = 0; i < 4; i++) parity ^= mat[i][j];
if (parity != mat[4][j]) {
colErr = j;
break;
}
}
if (rowErr != -1 && colErr != -1) {
cout << "⚠ Error detected at position: Row " << rowErr + 1 << ",
Column " << colErr + 1 << endl;
}
else if (rowErr != -1 || colErr != -1) {
cout << "⚠ Parity mismatch found, but unable to localize (Multiple
errors)\n";
}
else {
cout << "✅ No error detected. Parity checks passed.\n";
}
}

int main() {
srand(time(0));
string data;
cout << "Enter 16-bit binary dataword: ";
cin >> data;

if (data.length() != 16) {
cout << "Invalid input! Must be 16 bits.\n";
return 1;
}

Matrix senderMatrix = getDataMatrix(data);


addParity(senderMatrix);

printMatrix(senderMatrix, "\nSender Side Matrix (With Parity):");

int mode;
cout << "\nTransmission Mode:\n0. No Error\n1. Single Bit Error\n2. Two
Errors (Same Row)\n3. Three Errors (Different Rows/Columns)\n4. Four Bit
Rectangle Error\nEnter your choice: ";
cin >> mode;
Matrix receivedMatrix = simulateError(senderMatrix, mode);

printMatrix(receivedMatrix, "\nReceiver Side Matrix (Received):");

detectError(receivedMatrix);

return 0;
}

EXECUTION:

4. CHECKSUM:
AIM AND ALGORITHM:
PROGRAM:

#include <iostream>
#include <vector>
#include <string>
#include <cstdlib>
#include <ctime>
#include <sstream>
using namespace std;

unsigned short calculateChecksum(vector<unsigned short> words) {


unsigned int sum = 0;
for (auto word : words) sum += word;
while (sum >> 16) sum = (sum & 0xFFFF) + (sum >> 16);
return ~sum;
}

bool validateChecksum(vector<unsigned short> words, unsigned short


checksum) {
words.push_back(checksum);
return calculateChecksum(words) == 0xFFFF;
}

vector<unsigned short> parseBinaryString(string bin, int length) {


vector<unsigned short> words;
for (int i = 0; i < length; i += 16) {
string part = bin.substr(i, min(16, (int)bin.size() - i));
unsigned short val = 0;
for (char c : part) val = (val << 1) | (c == '1');
words.push_back(val);
}
return words;
}

vector<unsigned short> parseOctalString(string ocs, int count) {


vector<unsigned short> words;
for (int i = 0; i < ocs.length(); i += 6) {
string part = ocs.substr(i, min(6, (int)ocs.size() - i));
unsigned short val = stoi(part, nullptr, 8);
words.push_back(val);
}
return words;
}

vector<unsigned short> parseHexString(string hex, int count) {


vector<unsigned short> words;
for (int i = 0; i < hex.length(); i += 4) {
string part = hex.substr(i, min(4, (int)hex.size() - i));
unsigned short val = stoi(part, nullptr, 16);
words.push_back(val);
}
return words;
}

void flipRandomBit(vector<unsigned short>& words) {


int totalBits = words.size() * 16;
int bitPos = rand() % totalBits;
int wordIdx = bitPos / 16;
int b = 15 - (bitPos % 16);
words[wordIdx] ^= (1 << b);
}

void flipManualBit(vector<unsigned short>& words) {


int totalBits = words.size() * 16;
cout << "Enter bit position to flip (1 to " << totalBits << "): ";
int pos; cin >> pos;
pos--; // zero based
int wordIdx = pos / 16;
int b = 15 - (pos % 16);
words[wordIdx] ^= (1 << b);
}

int main() {
srand(time(0));
cout << "Choose data input:\n1. 16-bit Binary\n2. 10-Octet Octal\n3. 16-
Octet Hexadecimal\nEnter choice: ";
int choice; cin >> choice;

vector<unsigned short> words;


string inStr;
if (choice == 1) {
cout << "Enter 16-bit binary dataword: ";
cin >> inStr;
if (inStr.length() != 16) { cout << "Invalid – must be 16 bits.\n"; return 1;
}
words = parseBinaryString(inStr, inStr.length());
} else if (choice == 2) {
cout << "Enter 10-octet octal string (30 digits): ";
cin >> inStr;
if (inStr.length() != 30) { cout << "Invalid – must be 30 digits.\n"; return
1; }
words = parseOctalString(inStr, 10);
} else if (choice == 3) {
cout << "Enter 16-octet hex string (32 digits): ";
cin >> inStr;
if (inStr.length() != 32) { cout << "Invalid – must be 32 digits.\n"; return
1; }
words = parseHexString(inStr, 16);
} else {
cout << "Invalid choice!\n"; return 1;
}

unsigned short checksum = calculateChecksum(words);

cout << "\nSender Side:\n";


cout << "Words: ";
for (auto w : words) printf("%04x ", w);
cout << "\nChecksum: " << std::hex << checksum << std::dec << endl;

cout << "Transmission mode (0: Errorless, 1: Random error, 2: Manual


bit error): ";
int mode; cin >> mode;

vector<unsigned short> rxWords = words;


unsigned short rxChecksum = checksum;

if (mode == 1) {
flipRandomBit(rxWords);
cout << "Random bit flipped in the block.\n";
} else if (mode == 2) {
flipManualBit(rxWords);
cout << "Manual bit flipped in the block.\n";
} else {
cout << "No error introduced.\n";
}

cout << "\nReceiver Side:\n";


cout << "Received Words: ";
for (auto w : rxWords) printf("%04x ", w);
cout << "\nReceived Checksum: " << std::hex << rxChecksum <<
std::dec << endl;

if (validateChecksum(rxWords, rxChecksum))
cout << "Result of verification: ✅ No error detected\n";
else
cout << "Result of verification: ❌ Error detected\n";

return 0;
}

EXECUTION:

You might also like