What is C# exclusive or `^` usage?

Navid Rahmani picture Navid Rahmani · Jun 21, 2011 · Viewed 21.3k times · Source

Can anyone explain this operator with a good example?

I know what this operator is. I mean a real-life example.

Answer

Merlyn Morgan-Graham picture Merlyn Morgan-Graham · Jun 21, 2011

It is an implementation of the the logical operation exclusive disjunction

http://en.wikipedia.org/wiki/Exclusive_or

Exclusive disjunction is often used for bitwise operations. Examples:

  • 1 xor 1 = 0
  • 1 xor 0 = 1
  • 0 xor 1 = 1
  • 0 xor 0 = 0
  • 1110 xor 1001 = 0111 (this is equivalent to addition without carry)

As noted above, since exclusive disjunction is identical to addition modulo 2, the bitwise exclusive disjunction of two n-bit strings is identical to the standard vector of addition in the vector space (Z/2Z)^4.

In computer science, exclusive disjunction has several uses:

  • It tells whether two bits are unequal.
  • It is an optional bit-flipper (the deciding input chooses whether to invert the data input).
  • It tells whether there is an odd number of 1 bits ( is true iff an odd number of the variables are true).

(and a whole ton of other uses)