fork(4) download
  1. #include <stdio.h>
  2. #include <math.h>
  3.  
  4. void parityCheck(char* codeWord) {
  5. int parity[4] = {0}, i = 0, diffParity[4] = {0}, twoPower = 0, bitSum = 0;
  6.  
  7. // Stores # of 1's for each parity bit in array.
  8. parity[0] = (codeWord[2] - 48) + (codeWord[4] - 48) + (codeWord[6] - 48) + (codeWord[8] - 48) + (codeWord[10] - 48);
  9. parity[1] = (codeWord[2] - 48) + (codeWord[5] - 48) + (codeWord[6] - 48) + (codeWord[9] - 48) + (codeWord[10] - 48);
  10. parity[2] = (codeWord[4] - 48) + (codeWord[5] - 48) + (codeWord[6] - 48);
  11. parity[3] = (codeWord[8] - 48) + (codeWord[9] - 48) + (codeWord[10] - 48);
  12.  
  13. // Determines if sum of bits is even or odd, then tests for difference
  14. // from actual parity bit.
  15. for (i = 0; i < 4; i++) {
  16. twoPower = (int)pow((double)2, i);
  17.  
  18. if (parity[i] % 2 == 0)
  19. parity[i] = 0;
  20. else
  21. parity[i] = 1;
  22.  
  23. if ((codeWord[twoPower-1] - 48) != parity[i])
  24. diffParity[i] = 1;
  25. }
  26.  
  27. // Calculates the location of the error bit.
  28. for (i = 0; i < 4; i++) {
  29. twoPower = (int)pow((double)2, i);
  30. bitSum += diffParity[i]*twoPower;
  31. }
  32.  
  33. // Inverts bit at location of error.
  34. if (bitSum <= 11 && bitSum > 0) {
  35. if ((codeWord[bitSum-1] - 48))
  36. codeWord[bitSum-1] = '0';
  37. else
  38. codeWord[bitSum-1] = '1';
  39. }
  40. }
  41.  
  42. int pc(int codeWord) {
  43. int parity = 0, codeWordBit, bitPos;
  44. for (bitPos = 1; bitPos <= 11; ++bitPos) {
  45. codeWordBit = ((codeWord >> (bitPos - 1)) & 1);
  46. parity ^= bitPos*codeWordBit;
  47. }
  48. if (parity != 0)
  49. codeWord ^= 1 << (parity - 1);
  50. return codeWord;
  51. }
  52.  
  53. int main() {
  54. int c, f, b, errors = 0;
  55. char ew[12], cw[12], fw[12];
  56. ew[11] = cw[11] = fw[11] = '\0';
  57. for (c = 0; c != 1<<11; ++c) {
  58. f = pc(c);
  59. for (b = 0; b != 11; ++b) {
  60. ew[b] = cw[b] = '0' + ((c >> b)&1);
  61. fw[b] = '0' + ((f >> b)&1);
  62. }
  63. parityCheck(cw);
  64. for (b = 0; b != 11; ++b) {
  65. if (cw[b] != fw[b]) {
  66. printf("%.11s: expected %.11s got %.11s\n", ew, fw, cw);
  67. errors = 1;
  68. break;
  69. }
  70. }
  71. }
  72. if (errors == 0)
  73. printf("No erros :-)\n");
  74. return errors;
  75. }
  76.  
Success #stdin #stdout 0s 3340KB
stdin
Standard input is empty
stdout
No erros :-)