#include <stdio.h>
#include <math.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 has the parity bit
if (encoded[i] == 1) {
count++;
}
}
}
return count % 2; // Return the parity bit (even parity)
}
int main() {
int dataBits[7] = {1, 0, 0, 1, 1, 0, 1}; // Input data: 1001101
int dataSize = 7, totalBits = 11; // Hamming code requires 4 parity bits
int encoded[12] = {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);
}
// Display the encoded data
printf("Encoded Data: ");
for (int i = 1; i <= totalBits; i++) {
printf("%d", encoded[i]);
}
printf("\n");
return 0;
}
Comments
Post a Comment