rajath_pai

Hamming Code

Mar 9th, 2021 (edited)
188
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.74 KB | None | 0 0
  1. //Hamming code
  2.  
  3. #include<bits/stdc++.h>
  4. using namespace std;
  5.  
  6. int main(){
  7.     int a[12];
  8.     cout << "Enter 7 data bits to be transmitted\n";
  9.     for(int i = 11; i > 0; i--){
  10.         if(i!=1 && i!=2 && i!=4 && i!=8){
  11.             cin >> a[i];
  12.         }
  13.     }
  14.     a[1] = (a[3]+a[5]+a[7]+a[9]+a[11])%2;
  15.     a[2] = (a[3]+a[6]+a[7]+a[10]+a[11])%2;
  16.     a[4] = (a[5]+a[6]+a[7])%2;
  17.     a[8] = (a[9]+a[10]+a[11])%2;
  18.    
  19.     cout << "\nHamming code : ";
  20.     for(int i = 11; i > 0; i--){
  21.         cout << a[i] << " ";
  22.     }
  23.     cout << "\nDo you want to make any error (Y/N) : ";
  24.     char c;
  25.     cin >> c;
  26.     if(c == 'Y'){
  27.         cout << "\nEnter the position to make error : ";
  28.         int pos;
  29.         cin >> pos;
  30.         a[pos] = ((a[pos] == 0)?1:0);
  31.     }
  32.     cout << "\nData Received : ";
  33.     for(int i = 11; i > 0; i--){
  34.         cout << a[i] << " ";
  35.     }
  36.     int r1,r2,r4,r8;
  37.     r1 = (a[1]+a[3]+a[5]+a[7]+a[9]+a[11])%2;
  38.     r2 = (a[2]+a[3]+a[6]+a[7]+a[10]+a[11])%2;
  39.     r4 = (a[4]+a[5]+a[6]+a[7])%2;
  40.     r8 = (a[8]+a[9]+a[10]+a[11])%2;
  41.    
  42.     int error_position = (r8*8) + (r4*4) + (r2*2) + (r1*1);
  43.     if(error_position){
  44.         cout << "\nError detected at position " << error_position;
  45.         a[error_position] = ((a[error_position] == 0)?1:0);
  46.     }
  47.     else{
  48.         cout << "\nNo error occured\n";
  49.     }
  50.     cout << "\nFinal Data : ";
  51.     for(int i = 11; i > 0; i--){
  52.         cout << a[i] << " ";
  53.     }
  54. }
  55.  
  56. /*
  57. OUTPUT
  58.  
  59.  
  60. Enter 7 data bits to be transmitted
  61. 1 0 0 1 1 0 1
  62.  
  63. Hamming code : 1 0 0 1 1 1 0 0 1 0 1
  64. Do you want to make any error (Y/N) : Y
  65.  
  66. Enter the position to make error : 7
  67.  
  68. Data Received : 1 0 0 1 0 1 0 0 1 0 1
  69. Error detected at position 7
  70. Final Data : 1 0 0 1 1 1 0 0 1 0 1
  71.  
  72.  
  73.  
  74.  
  75. */
Add Comment
Please, Sign In to add comment