Added encoder function

Fixed XOR operator
TODO - Add boilerplate from syllabus file, then merge with main branch
This commit is contained in:
K 2024-07-29 19:57:00 +05:30
parent c1141bf596
commit b94dba6141
Signed by: notkshitij
GPG Key ID: C5B8BC7530F8F43F

View File

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