Pass the value to be checked in a file register (shown as "X" below). This register is NOT modified.
Will return NZ (and 0x80 in W) if the parity is odd, else returns Z and 0x00 in W
- Code: Select all
CheckParity:
swapf X, w ; John's idea: reducing byte to nibble
xorwf X, w ; " " " " " "
addlw 41H ; bit 1 becomes B0^B1 and bit 7 becomes B6^B7
iorlw 7CH ; for carry propagation from bit 1 to bit 7
addlw 2 ; Done! the parity bit is bit 7 of W
andlw 80H ; set NZ if odd parity, and leave 00 or 80 in W
return
Note, enhanced mid range chips (PIC16F1xxx) and also PIC18F chips can test bit 7 of W directly, so the final instruction is not necessary.
The following macro produces pretty similar code in Hitech C.
- Code: Select all
#define PARITY(b) ((((((b)^(((b)<<4)|((b)>>4)))+0x41)|0x7C)+2)&0x80)
This came from original discussions at http://www.microchip.com/forums/m4732.aspx
and http://www.microchip.com/forums/m4738.aspx and http://www.microchip.com/forums/m4762.aspx