Skip to content

Instantly share code, notes, and snippets.

@Sahas-Ananth
Last active March 27, 2021 13:41
Show Gist options
  • Save Sahas-Ananth/ad787365e7033fcd9f603e9e0f1153d8 to your computer and use it in GitHub Desktop.
Save Sahas-Ananth/ad787365e7033fcd9f603e9e0f1153d8 to your computer and use it in GitHub Desktop.
Error detection and correction
#include <stdio.h>
#include <stdio.h>
char data[5];
int encoded[8], edata[7], syndrome[3];
int hmatrix[3][7] = {1, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1};
char gmatrix[4][8] = {"0111000", "1010100", "1100010", "1110001"};
int main() {
int i = 0, j = 0;
char choice;
do {
printf("Hamming Code Encoding\nEnter 4 bit data: ");
scanf("%s", data);
printf("\nGenerator Matrix:\n");
for(i = 0; i < 4; i++) {
printf("\t%s\n", gmatrix[i]);
}
printf("\nEncoded data:\n");
for (i = 0; i < 7; i++) {
for (j = 0; j < 4; j++) {
encoded[i] += ( ((int)data[j]) * ((int)gmatrix[j][i]) );
}
encoded[i] %= 2;
printf("%d ", encoded[i]);
}
printf("\n\nHamming Code Decoding\nEnter Encoded bits as recieved: ");
for (i = 0; i < 7; i++) {
scanf("%d", &edata[i]);
}
for (i = 0; i < 3; i++) {
for (j = 0; j < 7; j++) {
syndrome[i] += (edata[j]*hmatrix[i][j]);
}
syndrome[i] %= 2;
}
for (j = 0; j < 7; j++) {
if ( (syndrome[0] == hmatrix[0][j]) && (syndrome[1] == hmatrix[1][j]) && (syndrome[2] == hmatrix[2][j]) ) {
break;
}
}
if (j != 7) {
printf("Error Recieved at bit number %d of the data\n", j+1);
edata[j] = !edata[j];
printf("The correct data should be:\n");
for (i = 0; i < 7; i++) {
printf("%d", encoded[i]);
}
}
else if (j ==7) {
printf("Data is error free!\n");
}
printf("\n\nDo you want to continue? [y/n]: ");
scanf("%s", &choice);
} while(choice == 'y');
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment