Full Version: Challenge: Identify ways to use XOR logical operator
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2 3
Many people never use exclusive-or (XOR). A professor at NYU, who had a PHD in Computer Science, while giving a class on "C" programming in 1985, described how it worked and then said "But who knows why you would ever use it." I almost had a fit.

Anyway, I sure you guru's can come up with many uses. But, let's keep them practical, i.e., give examples that make sense and are really useful.

Post a description of how you're using the XOR, and then give a coding example, which will usually be one line of code. Try not to be too critical of post submitted by others, and let's keep the BS down.

I'm sure you can use them somehow to make a "negative image" on the screen... Like turn all colours the opposite of what they are (really just 255-colour%). Then again, I proved myself wrong.
You mean like flip the bits in color%, by doing:
color% = color% xor 255

If that's what you want, this will do it.
Sure that works too. I win!
Circuit construction, adder circuits use a XOR gate for the sum value. ie.
A B | S C
0 0 | 0 0
0 1 | 1 0
1 0 | 1 0
1 1 | 0 1
Sum(S) = A XOR B, and Carry© = A AND B. Although at circuit construction level usually NAND gates are used for implementation because all other gates can be constructed using just NANDs which reduces cost.

Bitflipping, as mentioned by Seph. Taking a n-bit number and XORing it against a value where all the bits are set will flip all the bits in the number.

Anytime you need to determine if one or the other, but not both of two values is set. Although many programmers will simply write this long hand:
if A then
  if  not B then ...
  if B then ...
end if
You will probably find many examples of code that are actualling using exclusive-or logic without using the operator directly.
Swapping integers...
a% = 3
b% = 4
a% = a% XOR b%
b% = a% XOR b%
a% = a% XOR b%
now a% = 4 and b% = 3
Good example re circuit construction.

Your second example about doing things the long way reminds me of my favorite example which is for using a flip/flop switch. If the switch is on (a one), you want to turn it off. If the switch is off (zero), you want to turn it on.
flipflop = flipflop xor 1
Much simpler and no need to debug several if's.
Excellent. Your example is a classic. You must be an assembly language programmer. In assembler you find your self doing this method to swap the contents of two registers without having to use another intermediate register or time-consuming stores to memory.
In a sample assembly language, to swap registers a and b, it would look like this:
a xor b
b xor a
a xor b
Basically the same thing.
Edit Button! *dissolves into tears*
actually, moneo's example, by test, is an eensy weensy pee widdle bit slower than n% = 1 - n%

for 100000000 operations:
1-n: 11.19995 seconds
xor: 11.26001 seconds
Pages: 1 2 3