Hi,

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

My programing language is C#.

Hi,

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

My programing language is C#.

+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

sshow
2010-07-22 14:26:44

Will Dean
2010-07-22 14:44:27

@Will Dean: Thanks for clarifying.

sshow
2010-07-22 14:56:02
+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
```

Which is C7 in hexadecimal.

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

Chris B.
2010-07-22 14:31:27

A:

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

Prakash Kalakoti
2010-07-22 14:32:54

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.

Gabriel
2010-07-22 15:47:10

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.

Babar
2010-07-22 16:01:24

+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;
}
```

myermian
2010-07-22 16:03:01