#include <stdio.h>
// Function to calculate parity bits
int calculateParity(int encoded[], int size, int parityPosition) {
int count = 0;
for (int i = 1; i <= size; i++) {
if (i & parityPosition) { // Check if the bit position is covered by the parity bit
if (encoded[i] == 1) {
count++;
}
}
}
return count % 2; // Return the parity bit (even parity)
}
int main() {
int dataBits[11] = {1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1}; // Input data: 10010100101
int dataSize = 11, totalBits = 15; // Hamming code requires 4 parity bits
int encoded[16] = {0}; // Encoded array (1-indexed for simplicity)
// Map data bits into the encoded array (leave positions for parity bits)
int j = 0;
for (int i = 1; i <= totalBits; i++) {
if ((i & (i - 1)) == 0) { // Check if i is a power of 2 (parity bit position)
encoded[i] = 0; // Placeholders for parity bits
} else {
encoded[i] = dataBits[j++];
}
}
// Calculate and set parity bits
for (int i = 1; i <= totalBits; i <<= 1) { // Powers of 2 (1, 2, 4, 8)
encoded[i] = calculateParity(encoded, totalBits, i);
}
// Introduce an error at the 7th bit for testing
encoded[7] ^= 1; // Flip the 7th bit (simulate error)
// Display the encoded data
printf("Encoded Data with Error: ");
for (int i = 1; i <= totalBits; i++) {
printf("%d", encoded[i]);
}
printf("\n");
// Detect error in the encoded data
int errorPosition = 0;
for (int i = 1; i <= totalBits; i <<= 1) { // Powers of 2 (1, 2, 4, 8)
int parity = calculateParity(encoded, totalBits, i);
if (parity != 0) {
errorPosition += i;
}
}
// Display the error position
if (errorPosition == 0) {
printf("No errors detected.\n");
} else {
printf("Error detected at bit position: %d\n", errorPosition);
// Correct the error
encoded[errorPosition] ^= 1; // Flip the erroneous bit
printf("Corrected Encoded Data: ");
for (int i = 1; i <= totalBits; i++) {
printf("%d", encoded[i]);
}
printf("\n");
}
return 0;
}
Comments
Post a Comment