#include <stdio.h>
#include <math.h>
void parityCheck(char* codeWord) {
int parity[4] = {0}, i = 0, diffParity[4] = {0}, twoPower = 0, bitSum = 0;
// Stores # of 1's for each parity bit in array.
parity[0] = (codeWord[2] - 48) + (codeWord[4] - 48) + (codeWord[6] - 48) + (codeWord[8] - 48) + (codeWord[10] - 48);
parity[1] = (codeWord[2] - 48) + (codeWord[5] - 48) + (codeWord[6] - 48) + (codeWord[9] - 48) + (codeWord[10] - 48);
parity[2] = (codeWord[4] - 48) + (codeWord[5] - 48) + (codeWord[6] - 48);
parity[3] = (codeWord[8] - 48) + (codeWord[9] - 48) + (codeWord[10] - 48);
// Determines if sum of bits is even or odd, then tests for difference
// from actual parity bit.
for (i = 0; i < 4; i++) {
twoPower = (int)pow((double)2, i);
if (parity[i] % 2 == 0)
parity[i] = 0;
else
parity[i] = 1;
if ((codeWord[twoPower-1] - 48) != parity[i])
diffParity[i] = 1;
}
// Calculates the location of the error bit.
for (i = 0; i < 4; i++) {
twoPower = (int)pow((double)2, i);
bitSum += diffParity[i]*twoPower;
}
// Inverts bit at location of error.
if (bitSum <= 11 && bitSum > 0) {
if ((codeWord[bitSum-1] - 48))
codeWord[bitSum-1] = '0';
else
codeWord[bitSum-1] = '1';
}
}
int pc(int codeWord) {
int parity = 0, codeWordBit, bitPos;
for (bitPos = 1; bitPos <= 11; ++bitPos) {
codeWordBit = ((codeWord >> (bitPos - 1)) & 1);
parity ^= bitPos*codeWordBit;
}
if (parity != 0)
codeWord ^= 1 << (parity - 1);
return codeWord;
}
int main() {
int c, f, b, errors = 0;
char ew[12], cw[12], fw[12];
ew[11] = cw[11] = fw[11] = '\0';
for (c = 0; c != 1<<11; ++c) {
f = pc(c);
for (b = 0; b != 11; ++b) {
ew[b] = cw[b] = '0' + ((c >> b)&1);
fw[b] = '0' + ((f >> b)&1);
}
parityCheck(cw);
for (b = 0; b != 11; ++b) {
if (cw[b] != fw[b]) {
printf("%.11s: expected %.11s got %.11s\n", ew, fw, cw);
errors = 1;
break;
}
}
}
if (errors == 0)
printf("No erros :-)\n");
return errors;
}