-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHamming_Code
More file actions
71 lines (59 loc) · 2.07 KB
/
Copy pathHamming_Code
File metadata and controls
71 lines (59 loc) · 2.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include <stdio.h>
// Function to calculate parity bits
void generateHammingCode(int data[], int code[]) {
// Place data bits at non-parity positions: 3,5,6,7,9,10,11 (1-based)
code[2] = data[0];
code[4] = data[1];
code[5] = data[2];
code[6] = data[3];
code[8] = data[4];
code[9] = data[5];
code[10] = data[6];
// Calculate parity bits at positions 1, 2, 4, and 8 (0-based: 0,1,3,7)
code[0] = code[2] ^ code[4] ^ code[6] ^ code[8] ^ code[10];
code[1] = code[2] ^ code[5] ^ code[6] ^ code[9] ^ code[10];
code[3] = code[4] ^ code[5] ^ code[6];
code[7] = code[8] ^ code[9] ^ code[10];
}
// Function to detect and correct single-bit errors
int detectAndCorrect(int code[]) {
int p1 = code[0] ^ code[2] ^ code[4] ^ code[6] ^ code[8] ^ code[10];
int p2 = code[1] ^ code[2] ^ code[5] ^ code[6] ^ code[9] ^ code[10];
int p4 = code[3] ^ code[4] ^ code[5] ^ code[6];
int p8 = code[7] ^ code[8] ^ code[9] ^ code[10];
int errorPos = p8 * 8 + p4 * 4 + p2 * 2 + p1 * 1;
return errorPos;
}
int main() {
int data[7];
int code[11] = {0};
printf("SENDER SIDE:\n");
printf("Enter 7 data bits (space-separated, e.g., 1 0 1 1 0 0 1): ");
for (int i = 0; i < 7; i++) {
scanf("%d", &data[i]);
}
generateHammingCode(data, code);
printf("Generated 11-bit Hamming Code (to send): ");
for (int i = 0; i < 11; i++) {
printf("%d ", code[i]);
}
printf("\n\nRECEIVER SIDE:\n");
int receivedCode[11];
printf("Enter the 11-bit Hamming code received (space-separated): ");
for (int i = 0; i < 11; i++) {
scanf("%d", &receivedCode[i]);
}
int errorPos = detectAndCorrect(receivedCode);
if (errorPos == 0) {
printf("\nNo error detected in received data.\n");
} else {
printf("\nError detected at position: %d\n", errorPos);
receivedCode[errorPos - 1] ^= 1; // Correct the error
printf("Corrected Code: ");
for (int i = 0; i < 11; i++) {
printf("%d ", receivedCode[i]);
}
printf("\n");
}
return 0;
}