288

7
+5  Q:

## When to use "^" operator

Hi,

What is the operator below ^? When to use it?

My programing language is C#.

+1  A:
+9  A:

`^` is a Logical XOR Operator if the operands are bools, otherwise it's a Bitwise XOR Operator

Binary ^ operators are predefined for the integral types and bool. For integral types, ^ computes the bitwise exclusive-OR of its operands. For bool operands, ^ computes the logical exclusive-or of its operands; that is, the result is true if and only if exactly one of its operands is true.

http://msdn.microsoft.com/en-us/library/zkacc7k1.aspx

@Will Dean: Thanks for clarifying.
+3  A:

It's the XOR operator. It's used in bitwise operations, where the result is true if the left side is true or the right side is true, but false if both are true or both are false. So `0xf8 ^ 0x3f` would be:

``````1111 1000
0011 1111
---------
1100 0111
``````

In general, if you're not doing bitwise arithmetic, you won't need to worry about it.

You forgot to add that it's also false if BOTH are false.
A:

You can find some good examples on this operator at http://www.blackwasp.co.uk/CSharpLogicalBitwiseOps.aspx

A:

I think of it as a binary operator just like ||, &&, etc...

If I were writing logic and ended up with:

``````if( (condition1 && !condition2) || (condition2 && !condition1) )
{
}
``````

I might rewrite it as:

``````if( condition1 ^ condition2)
{
}
``````

That said, I'd take it on a case by base basis and weigh the benefit of brevity vs. potential obfuscation due to relative obscurity.

A:

Its Exclusive OR (XOR) operator as mentioned by others. Here is the truth table for XOR

``````P    Q    P^Q
T    T     F
T    F     T
F    T     T
F    F     F
``````

Note that P^Q is equal to P!=Q. Sometimes P!=Q is used in the code instead of XOR operator.

+1  A:
• It is often used as a way to "flip bits" by XORing it with 1 (to flip), 0 (to keep). Usually this is useful in encryption/decryption/hashing. ** THIS IS ACTUALLY USEFUL **

Example:

``````101 ^
110
-----
011   //Flip the first 2, keep the 3rd
``````
• It can also be used for a swapping method (though, using the standard way and generics is probably more ideal):

Example:

``````int myMoney = 10;
int yourMoney = 50;
Swap(myMoney, yourMoney)

public void Swap(ref int a, ref int b) //No 'temp' variable necessary
{
a ^= b;
b ^= a;
a ^= b;
}
``````
• It is used in binary arithmetic. ** THIS IS ACTUALLY USEFUL **

• Flip a bool (though, I'd rather use bool x = true; x != x;

Example:

``````public bool flip(ref bool b)
{
b ^= true;
}
``````