This may be a stupid question but I can’t seem to figure this out.
I’ve written a program the takes a char as input, outputs the char and its hexadecimal value then checks for even parity and sets the parity bit to 1 and again outputs the “new” char and it’s hex value. However using printf and %c doesn’t seem to be the way to go and I don’t understand why or how to fix it, so I would very much appreciate if someone could explain why not and what I should be doing instead. Oh and feel free to comment on the code I am learning after all so criticism is always good 🙂
int checkParity(unsigned char myChar); //returns 0 if even 1 if odd
int main() {
int i;
unsigned char input;
printf("Enter char: ");
scanf("%c", &input);
/* print unchanged char and hex with */
printf("c7: %c ", input);
printf("hex: %x \n", input);
/*if parity is odd*/
if(checkParity(input)){
/*change to even*/
input = (input|0x80);
}
/* print char and hex even parity */
printf("c8: %c ", input);
printf("hex: %x \n", input);
return 0;
}
int checkParity(unsigned char myChar){
int i;
int parity = 0;
while(myChar){ //while myChar != 0
parity += (myChar&1); //add result of myChar AND 1 to parity
myChar = myChar>>1; //shift bits left by 1
}
//printf("parity equals: %d\n", parity);
if(parity%2){ // if odd parity
return 1;
}
else { //even parity
return 0;
}
}
What are parity bits?
Parity bits are a simple form of error-checking that can be used, for example, when you transmit data from one machine to another. If both machines agree on, say, even parity, then the receiver will know that any incoming characters that don’t have even parity were received in error. However, parity of any type can only identify an odd number of erroneous bits: two errors in a single character will cancel each other, and the resulting parity will be correct. Moreover, the receiver cannot determine which bit (or bits) are incorrect; parity provides error detection, but not error correction.
How should received data be processed?
The receiver should calculate and validate the parity of each incoming character. If it detects a character with invalid parity, it should indicate the error somehow. In the best case, it may be able to ask the transmitter to re-transmit the character.
Once the character is validated, the receiver must strip the parity bit before passing the character on for further processing. This is because, since the parity bit is used for error detection, it is “lost” from the data payload. Thus, enabling parity will reduce the number of available data values by half. For example, 8 bits can have one of 256 possible values (0 – 255). If one bit is used for parity, only 7 bits remain to encode the data, leaving only 128 valid values.
Since you asked for comments/criticism, here’s a revised, commented version of your code: