Manually Computing XOR (Exclusive OR) using AND / OR operators

Started by kevin, July 27, 2016, 11:53:28 AM

Previous topic - Next topic

kevin

 Manually Computing XOR (Exclusive OR) using AND / OR operators


   Ever wonder how to create your own XOR function using only AND and OR ?



PlayBASIC Code: [Select]
   //   Run in DEBUG MODE to see output

For lp =0 to 1000

A=(RND($ffff) << 16) or RND($ffff)
B=(RND($ffff) << 16) or RND($ffff)

Result1= A Xor B
Result2= Xor2(A,B)
s$ ="Test #"+STr$(lp)+" "
s$+=hex$(Result1) + " "+ hex$(Result2)

if Result1!=Result2
s$+="Failed"
endif
print s$
#print s$


Sync
next

Sync
waitkey




Function Xor2(A,B)

// Mask input bits together to find the common bits in both
Mask = A and B

// Invert Mask (remember 2's complement :) )
InvertedMASK = -1 - MASK

// Clean bits out that appear in both, since we should only
// return set bits when a bit is 1/0 or 0/1
A= A And InvertedMask
B= B And InvertedMask

// Or them together
Result = A or B
EndFunction Result