XORing the bits of a value with a bit mask is one way to compute parity.
Code:
unsigned short mask;
unsigned int result = 0;
for ( mask = 0x40; mask; mask >>= 1 )
{
result ^= !!(mask & value);
}
The result of this will be 0 if there is an even number of bits in value, and 1 if there is an odd number of bits in value. But this is even parity; to get odd parity, invert the result.
Code:
if ( odd )
{
result = !result;
}
A way to combine this result with the initial value, in this situation, could be to OR the result at the MSB with the original value.
Code:
value |= result << 7;
About the only thing I may have left out is a function declaration and return value.
Code:
unsigned short parity(unsigned short value, int odd)
{
/* ... */
return value;
}
Or a test program that might produce these results:
parity(0x4E,1) = 0xCE
parity(0x19,1) = 0x19