Advertisement
Eternoseeker

CRC code Chinmay

Jun 7th, 2023 (edited)
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.43 KB | Source Code | 0 0
  1. #include <iostream>
  2. #include <string>
  3.  
  4. using namespace std;
  5.  
  6. // Function to perform CRC error detection
  7. string performCRC(const string& data, const string& divisor) {
  8.     string dividend = data;
  9.  
  10.     int divisorLength = divisor.length();
  11.     int dataLength = data.length();
  12.  
  13.     // Append zeros to the dividend to match the divisor length
  14.     for (int i = 0; i < divisorLength - 1; i++) {
  15.         dividend += '0';
  16.     }
  17.  
  18.     // Perform division
  19.     for (int i = 0; i < dataLength; i++) {
  20.         if (dividend[i] == '1') {
  21.             for (int j = 0; j < divisorLength; j++) {
  22.                 dividend[i + j] = (dividend[i + j] == divisor[j]) ? '0' : '1';
  23.             }
  24.         }
  25.     }
  26.  
  27.     // Extract the remainder (CRC)
  28.     string remainder = dividend.substr(dataLength, divisorLength - 1);
  29.     return remainder;
  30. }
  31.  
  32. int main() {
  33.     string data1;
  34.     string divisor;
  35.     string data2;
  36.     cout << "Enter data (7/8 bits): ";
  37.     cin >> data1;
  38.  
  39.     cout << "Enter divisor: ";
  40.     cin >> divisor;
  41.  
  42.     string crc1 = performCRC(data1, divisor);
  43.  
  44.     cout << "CRC (Remainder): " << crc1 << endl;
  45.  
  46.     cout << "Enter the received packet: ";
  47.     cin >> data2;
  48.  
  49.     string crc2 = performCRC(data2, divisor);
  50.     cout << "New remainder: " << crc2 << endl;
  51.  
  52.     if (crc2.find_first_not_of('0') == string::npos) {
  53.         cout << "No error" << endl;
  54.     } else {
  55.         cout << "Error" << endl;
  56.     }
  57.     return 0;
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement