Shortest way to calculate parity on a PIC16F

Shortest way to calculate parity on a PIC16F

Postby ric » Sun Jun 01, 2014 11:24 am

Ultimate code to calculate parity on a mid-range PIC (which cannot test bits of the W register directly)
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
        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

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
and and
Latest test project, an LED matrix display made from one reel of addressable LEDs. here
User avatar
Verified identity
Posts: 528
Joined: Sat May 24, 2014 2:35 pm
Location: Melbourne, Australia
PIC experience: Professional 5+ years with MCHP products

Return to Tips and Tricks

Who is online

Users browsing this forum: No registered users and 1 guest