Skip to content

Instantly share code, notes, and snippets.

@avi-arora
Created August 29, 2022 08:27
Show Gist options
  • Save avi-arora/beaf91c650fe47e8a9469e81dd200517 to your computer and use it in GitHub Desktop.
Save avi-arora/beaf91c650fe47e8a9469e81dd200517 to your computer and use it in GitHub Desktop.
crc.cpp
#include <iostream>
#include <bitset>
using namespace std;
string POLYNOMIAL = "10001000000100001";
string TextToBinaryString(string words) {
string binaryString = "";
for (char& _char : words) {
binaryString +=bitset<8>(_char).to_string();
}
return binaryString;
}
string ComputeCRC(string bin_msg){
string encoded = "";
int msg_len = bin_msg.length(), poly_len = POLYNOMIAL.length();
encoded += bin_msg;
for(int i=1; i <= poly_len - 1; i++){
encoded += '0';
}
for(int i = 0; i <= encoded.length() - poly_len;){
for(int j = 0; j < poly_len; j++){
encoded[i+j] = encoded[i+j] == POLYNOMIAL[j] ? '0' : '1';
}
for(; i < encoded.length() && encoded[i] != '1'; i++);
}
return encoded.substr(encoded.length() - poly_len + 1);
}
void receiver() {
string msg, crc;
cout << "Enter message : ";
getline(cin, msg);
cout << "Enter crc : ";
getline(cin, crc);
string bin_msg = TextToBinaryString(msg);
string computed_crc = ComputeCRC(bin_msg + crc);
cout << "Computed CRC: " << computed_crc << endl;
if(computed_crc.find('1') != std::string::npos){
cout << "Error Detected. (Msg Rejected)" << endl;
}else{
cout << "No Error Detected. (Msg Accepted)" << endl;
}
}
void sender(){
string msg;
cout << "Enter the message : ";
getline(cin, msg);
string bin_msg = TextToBinaryString(msg);
string sender_crc = ComputeCRC(bin_msg);
cout << sender_crc << endl;
}
int main(int argc, char const *argv[])
{
/* code */
cout << "Sender" << endl;
sender();
cout << "Receiver" << endl;
receiver();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment