Page 1 of 1

XOR in BASIC

Posted: Wed Oct 04, 2023 3:08 pm
by Jeff-20
Two variations of XOR (in BAISC) have been suggested to me. First:

Code: Select all

(X AND NOT Y) OR (NOT X AND Y)
Then a reviewer (Daivd via GoodReads) suggested this would be better:

Code: Select all

(X OR Y) - (X AND Y)
I would like to have different perspectives. Is this a better solution and should it replace the first one?

Re: XOR in BASIC

Posted: Wed Oct 04, 2023 3:48 pm
by Mike
Is this a better solution and should it replace the first one?
In a strictly mathematical sense, the second definition is worse, as it inappropriately mixes logic and arithmetic operators, and subtly relies on certain properties of the underlying 2s-complement arithmetic to work correctly.

The first definition is the canonical one you will find in many textbooks about mathematical logic, along with the equivalent definition "X XOR Y := (X OR Y) AND NOT (X AND Y)". Operator priorities in BASIC are such that you can omit the parentheses with "(X AND NOT Y) OR (NOT X AND Y)" giving "X AND NOT Y OR NOT X AND Y" (NOT binds stronger than AND, AND binds stronger than OR), which are 9 bytes of tokenized text. With "(X OR Y) - (X AND Y)", you can't omit the parentheses (subtraction binds stronger than either AND or OR), thus the second version needs at least 11 bytes of tokenized text.

The second version leaves you with some fewer characters when LISTed. Any speed difference will be marginal.