XOR in BASIC

Basic and Machine Language

Moderator: Moderators

Post Reply
User avatar
Jeff-20
Denial Founder
Posts: 5759
Joined: Wed Dec 31, 1969 6:00 pm

XOR in BASIC

Post 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?
High Scores, Links, and Jeff's Basic Games page.
User avatar
Mike
Herr VC
Posts: 4841
Joined: Wed Dec 01, 2004 1:57 pm
Location: Munich, Germany
Occupation: electrical engineer

Re: XOR in BASIC

Post 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.
Post Reply