Code:
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
/*global vars */
int length;
int parity;
char *hamming_string=NULL;
int enter_params(){
/* declare local vars */
/* prompt for length of hamming code, parity */
printf("Enter the length of the hamming code: ");
scanf("%d", &length);
printf("Enter the parity (0=even, 1-odd): ");
scanf("%d", &parity);
/* alocate space for hamming code */
hamming_string=(char*)malloc(length*sizeof(char));
return;
}
int check(){
/* declare local vars */
int i;
int j;
int k;
int parity_check;
int error_bit;
printf("Enter the Hamming code: ");
scanf("%s", hamming_string);
for(i=1; i<length; i = i*2){
parity_check=parity;
error_bit=0;
for(j=i; j<length; j=j + 2*i){
for(k=j; k<i+2*i&&k<length; k++){
if(k != i){
parity_check = parity_check ^ (hamming_string[length - k] - '0');}
}
}
error_bit= error_bit + (parity_check ^ (hamming_string[length - i] - '0')*i);
}
if(error_bit > 0){
if(hamming_string[length-error_bit]=='0'){
printf("There is an error in bit: %d", hamming_string[length-error_bit]=='0');
hamming_string[length-error_bit]='1';
printf("\n");
}
else{
hamming_string[length-error_bit]='0';
}
printf("The corrected Hamming code is: %s", hamming_string);
printf("\n");
}
else{
printf("There is no bit error");
printf("\n");
}
return;
}
int quit(){
if(hamming_string!=NULL){
free(hamming_string);
}
}
int main()
{
int interface = 0;
while(interface != 3)
{
{
printf("Error detection/correction:\n");
printf("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n");
printf("1) Enter parameters\n");
printf("2) Check Hamming code\n");
printf("3) Exit\n");
printf("\n Enter Selection: ");
scanf("%d", &interface);
}
switch(interface)
{
case 1: enter_params(); break;
case 2: check(); break;
case 3: quit(); break;
default: break;
}
}
return 1;
}
Hi, I enter length 7 for the Hamming code and enter 0 for Parity.
When I choose selection 2, I enter 1000110 for the Hamming code and I get a message that there is no bit error. The answer I am supposed to get is there is an error in bit 6 and the corrected Hamming code is 11000110.
the funny thing is that I get the correct answer when I enter 1 for Parity and the same length (7) and Hamming code(1000110). The correct answer for that problem is error in bit 1 and the corrected Hamming code is 1000111
thank you for your help!