0% found this document useful (0 votes)
3 views2 pages

Hamming Code

The document is a C program that generates a Hamming code from a 4-bit input data and checks for errors in a received 7-bit Hamming code. It calculates parity bits for error detection and correction using even parity. If an error is detected, it identifies the position of the error and corrects it, displaying the corrected Hamming code.

Uploaded by

anushka13058
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views2 pages

Hamming Code

The document is a C program that generates a Hamming code from a 4-bit input data and checks for errors in a received 7-bit Hamming code. It calculates parity bits for error detection and correction using even parity. If an error is detected, it identifies the position of the error and corrects it, displaying the corrected Hamming code.

Uploaded by

anushka13058
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

#include <stdio.

h>
#include <string.h>

int main()
{
char data[10];
char hamming[15];
int i, p1, p2, p4;
int error_pos = 0;

clrscr();

printf("Enter 4-bit data: ");


scanf("%s", data);

/* Positioning data bits


Positions: 1 2 3 4 5 6 7
Bits: p1 p2 d1 p4 d2 d3 d4
*/

hamming[0] = '0'; /* unused */


hamming[3] = data[0]; /* d1 */
hamming[5] = data[1]; /* d2 */
hamming[6] = data[2]; /* d3 */
hamming[7] = data[3]; /* d4 */

/* Calculate parity bits (Even parity) */


p1 = (hamming[3] + hamming[5] + hamming[7] - 3 * '0') % 2;
p2 = (hamming[3] + hamming[6] + hamming[7] - 3 * '0') % 2;
p4 = (hamming[5] + hamming[6] + hamming[7] - 3 * '0') % 2;

hamming[1] = p1 + '0';
hamming[2] = p2 + '0';
hamming[4] = p4 + '0';

printf("\nGenerated Hamming Code: ");


for (i = 1; i <= 7; i++)
printf("%c", hamming[i]);

/* Receiver Side */
printf("\n\nEnter received 7-bit Hamming code: ");
for (i = 1; i <= 7; i++)
scanf(" %c", &hamming[i]);

p1 = (hamming[1] + hamming[3] + hamming[5] + hamming[7] - 4 * '0') % 2;


p2 = (hamming[2] + hamming[3] + hamming[6] + hamming[7] - 4 * '0') % 2;
p4 = (hamming[4] + hamming[5] + hamming[6] + hamming[7] - 4 * '0') % 2;

error_pos = p4 * 4 + p2 * 2 + p1 * 1;

if (error_pos == 0)
printf("\nNo error detected.");
else
{
printf("\nError detected at position: %d", error_pos);

/* Correct the error */


hamming[error_pos] =
(hamming[error_pos] == '0') ? '1' : '0';
printf("\nCorrected Hamming Code: ");
for (i = 1; i <= 7; i++)
printf("%c", hamming[i]);
}

getch();
return 0;
}

Output Example
Enter 4-bit data: 1011
Generated Hamming Code: 0110011

Enter received 7-bit Hamming code: 0110011


No error detected.

With error:

Error detected at position: 3


Corrected Hamming Code: 0110011

You might also like