Quick Post: XOR in Commodore BASIC 2

Maybe on a weekday evening you find yourself in need of some exclusive OR (XOR) operations on a machine that curiously doesn't have one built in.

Like... BASIC 2 on the Commodore VIC-20 and 64! Why it doesn't have XOR is probably just another example of trying to save precious ROM space.

I'm working on something for next week on the VIC-20 and I don't have a cartridge like Simon's BASIC like I do when I'm working on the 64 to give us Exclusive OR. It's actually called `EXOR` in Simon's, presumably to make things as confusing as possible.

Method one - use the logic operators we DO have

We do have the tools in BASIC 2 to do an XOR. We just need to string an `OR` and a `NOT AND` together. It's the same:

``````10 X=133:Y=34
20 PRINT(X OR Y)AND NOT(X AND Y)
``````

Easy enough right?

Method two - Add with carry out

The second one isn't terribly intuitive if you've not done much assembly programming, but if you use the carry from a binary addition it's an XOR:

``````10 X=133:Y=34
20 PRINT(X+Y)-2*(X AND Y)
``````

Which is faster?

Just for fun, I compared 500 operations in each to see which is faster: pure logic, the addition method and Simon's BASIC.

The results are maybe surprising:

Without SIMON's

Simon's BASIC appears to make BASIC slower for this operation, so here's the "benchmark" without it.

VIC-20

Obviously the VIC doesn't have SIMON's, but it does have the other two. And for this sort of thing a VIC-20 is faster than a 64:

That's it!

Happy coding (I told you it was quick)

Extra... fun?

Can we make this faster? We can a little. Let's remove the SIMON's lines and add a variable N to hold the count. Also initialize the X and Y variables.

128 needs some love

And just for completeness...

Integers would be faster you say?

You'd think so, but integers in Commodore BASIC are basically worthless. All operations are in floating point, so an integer is converted to a float, the operation performed and then converted back. I don't know if I'm aware of a situation where it's faster for anything.

Evidence: