Created
January 7, 2019 03:39
Star
You must be signed in to star a gist
Hamming Code Implementation in C+
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Post at : https://medium.com/code01/hamming-code-implementation-in-c-c16f3d038ba1 | |
#include <iostream> | |
#include <stdlib.h> | |
#include <stdio.h> | |
#include <math.h> | |
using namespace std; | |
int | |
main () | |
{ | |
int a, b, c[30], d, r = 0, d1; //Max bits here i kept is 30 | |
cout << " Enter the No of Data Bits you want to Enter : "; | |
cin >> a; | |
while (a + r + 1 > pow (2, r)) | |
{ | |
r++; | |
} | |
cout << "No of data bits to be added " << r << " : Total Bits :" << a + | |
r << endl; | |
cout << " Enter the Data Bits One by One :" << endl; | |
for (int i = 1; i <= a; ++i) | |
cin >> c[i]; | |
cout << endl << " Data bits entered : "; | |
for (int i = 1; i <= a; ++i) | |
cout << c[i] << " "; | |
cout << endl; | |
int data[a + r]; | |
d = 0; | |
d1 = 1; | |
for (int i = 1; i <= a + r; ++i) | |
{ | |
if ((i) == pow (2, d)) | |
{ | |
data[i] = 0; | |
++d; | |
} | |
else | |
{ | |
data[i] = c[d1]; | |
++d1; | |
} | |
} | |
cout << " Data Bits are Encoded with Parity bits(0): "; | |
for (int i = 1; i <= a + r; ++i) | |
cout << data[i] << " "; | |
d1 = 0; | |
int min, max = 0, parity, s, j; | |
/*Parity Bit Calculation */ | |
for (int i = 1; i <= a + r; i = pow (2, d1)) | |
{ | |
++d1; | |
parity = 0; | |
j = i; | |
s = i; | |
min = 1; | |
max = i; | |
for (j; j <= a + r;) | |
{ | |
for (s = j; max >= min && s <= a + r; ++min, ++s) | |
{ | |
if (data[s] == 1) | |
parity++; | |
} | |
j = s + i; | |
min = 1; | |
} | |
if (parity % 2 == 0) // Even Parity | |
{ | |
data[i] = 0; | |
} | |
else | |
{ | |
data[i] = 1; | |
} | |
} | |
cout << endl << " Hamming codeword bits for even parity are : "; | |
for (int i = 1; i <= a + r; ++i) | |
cout << data[i] << " "; | |
cout << endl << endl; | |
} | |
//End |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment