Last active
December 28, 2015 16:59
-
-
Save thomastaylor312/7532828 to your computer and use it in GitHub Desktop.
A small, slightly hacky C program to calculate the parity of data and then compare it using modified data. This will probably be used for some sort of homework assignment.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
//Code for calculate parity from http://graphics.stanford.edu/~seander/bithacks.html#ParityNaive | |
unsigned int calculateParity(int data) { | |
unsigned int parity = 1; //Even parity to start | |
while (data) { | |
parity = !parity; | |
data = data & (data - 1); | |
} | |
return parity; | |
} | |
//Make sure to understand why I change the data I do. I would change it to your own. It isn't too hard | |
int main(void) { | |
unsigned int originalData = 0xDE; // word value to compute the parity of | |
unsigned int parity = calculateParity(originalData); | |
printf("%s: %#02x\n", "Original Data", originalData); | |
printf("%s: %d\n", "Parity Bit", parity); | |
//Add parity bit | |
unsigned int parityData = originalData << 1; | |
parityData = parityData | parity; | |
//Do parity checks | |
int result; | |
int parityBit = parityData & 1; | |
result = parityBit == calculateParity(originalData); | |
printf("%s (%#02x): %d\n", "Original Data OK", originalData, result); | |
//Modify the data to make it bad and do the parity check again (1 bit) | |
originalData = originalData + 1; | |
result = parityBit == calculateParity(originalData); | |
printf("%s (%#02x): %d\n", "1 bit error OK", originalData, result); | |
//2 bit | |
originalData = 0xFF; | |
result = parityBit == calculateParity(originalData); | |
printf("%s (%#02x): %d\n", "2 bit error OK", originalData, result); | |
//3 bit | |
originalData = 0xFD; | |
result = parityBit == calculateParity(originalData); | |
printf("%s (%#02x): %d\n", "3 bit error OK", originalData, result); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment