Go lightly on the exclusive ors (XOR)

Randall Maas 7/1/2010 10:21:33 AM

When creating a code style guide, one of the considerations is the preferred choice between different constructs that achieve the same thing. I usually prefer an idiom that is easier to understand, or can be maintained over the long term, even if it is slightly more verbose.

To illustrate, I suggest not using XOR's in production (non- throw away) code:

   PORTA ^= 1 << 4;

Why?

Some microcontrollers have more than one port. On the PIC18's, for instance, check the pin state on PORTA, but set it on LATA. The use of dual ports is supports checking for an open or shorted pin on the output. (i.e., the setting of the driver is set and read from different registers that read the pins actual state).

Second, and just as important, is code maintenance after principle development. I've found that there are many people problems with XOR constructions. These are reasonable people, doing continuation (adding/removing features, fixing bugs, making custom changes, etc), or using the code to create manufacturing test code, or reading the code as part of electrical design, have. The code has to be able to read by them.

The code would then be:

#define MyPin (1 << 4)


   if (PORTA & MyPin)
     LATA &= ~ MyPin;
    else
     LATA |= MyPin;

Again, I prefer a guideline rather than an absolute rule. Maybe the XOR is a better approach, or clearer.

And certainly XOR is very very useful in algorithms like LFSR, CRC, forward error correction codes, Reed-Solomon, RAID, and so forth.