2024-07-29 19:27:12 +05:30
|
|
|
#include <iostream>
|
|
|
|
#include <cstring>
|
|
|
|
using namespace std;
|
|
|
|
|
|
|
|
string XOR(string data, string key) {
|
|
|
|
// Dividend is data
|
|
|
|
// Divisor is the primary key, i.e. the key
|
|
|
|
string result = "";
|
2024-07-29 19:57:00 +05:30
|
|
|
int dataLen = data.length();
|
|
|
|
int keyLen = key.length();
|
|
|
|
|
|
|
|
// Perform XOR operation
|
|
|
|
for (int i=0; i<keyLen; i++) {
|
|
|
|
if (i < dataLen) {
|
|
|
|
// Only perform XOR if within the length of data
|
|
|
|
if (data[i] == key[i]) {
|
|
|
|
result += '0';
|
|
|
|
}
|
|
|
|
else {
|
|
|
|
result += '1';
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
// If data length exceeded, append the key
|
|
|
|
result += key[i];
|
2024-07-29 19:27:12 +05:30
|
|
|
}
|
|
|
|
}
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
|
2024-07-29 19:57:00 +05:30
|
|
|
string encoder(string data, string key) {
|
|
|
|
int keyLen = key.length();
|
2024-07-29 19:27:12 +05:30
|
|
|
|
2024-07-29 19:57:00 +05:30
|
|
|
// Append n-1 zeroes to the data
|
|
|
|
string dataWithZeroes = data + string(keyLen-1, '0');
|
2024-07-29 19:27:12 +05:30
|
|
|
|
2024-07-29 19:57:00 +05:30
|
|
|
// Perform XOR operation with the key
|
|
|
|
string remainder = XOR(dataWithZeroes, key);
|
2024-07-29 19:27:12 +05:30
|
|
|
|
2024-07-29 19:57:00 +05:30
|
|
|
// Get the remainder (last n-1 bits)
|
|
|
|
string crc = remainder.substr(remainder.length() - (keyLen-1));
|
2024-07-29 19:27:12 +05:30
|
|
|
|
2024-07-29 19:57:00 +05:30
|
|
|
// Append the CRC to the original data
|
|
|
|
return data + crc;
|
2024-07-29 19:27:12 +05:30
|
|
|
}
|
2024-07-29 19:57:00 +05:30
|
|
|
|
|
|
|
int main() {
|
|
|
|
string data, key;
|
|
|
|
|
|
|
|
cout << endl << "Enter data:\t";
|
|
|
|
getline(cin, data);
|
|
|
|
cout << "Enter primary key:\t";
|
|
|
|
getline(cin, key);
|
|
|
|
|
|
|
|
string messageToSend = encoder(data, key);
|
|
|
|
cout<<endl<<"--------------------"<<endl;
|
|
|
|
cout<<"Message to be sent:\t"<<messageToSend;
|
|
|
|
cout<<endl<<"--------------------"<<endl;
|
|
|
|
|
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
|
|
|
|
// TODO:
|
|
|
|
// - Check if input data is actually binary
|