??? 03/24/06 07:53 Read: times |
#112938 - How about a portable solution? Responding to: ???'s previous message |
I pondered this issue recently. Whilst it is very straightforward in assembler as mentioned, it doesn't make for very portable code! I trolled the web for an elegant solution but there was nothing that grabbed me. Simply, parity is the addition of all the bits - the result is a bit. Depending on if you invert this bit, you get even or odd parity. So in general 'c', one would get: char do_parity(char val) { char a,parity,tmp; tmp = val; //get a copy to play with parity = 0; //start with parity = 1 for odd parity result for(a=0; a<7;a++) { if (tmp & 0x01) { parity ^= 0x01; //flip the parity bit for each '1' bit } tmp>>=1; //shift next bit } return parity; } Not super efficient is it? Hopefully the compiler is smart enough to figure that you are calculating parity and substitutes the more optimum code!! |