What are the | and ^ operators used for? [duplicate]

Possible Duplicate:
What are bitwise operators?

Recently I came across a few samples that used the | and ^ operator. I am guessing these are or and negation operators.

So what actually do these operators stands for?


  • | = (bitwise/non-short-circuiting) "or"
  • ^ = "xor"

and for info, "not" (bitwise negation) is ~


If you apply it to integral types, they are bitwise or and xor operator. However if you apply them to boolean types, they are logical or and xor. Look at an explanation of or operator and xor operator

You can get more details on boolean operations from the wikipedia truth table


MSDN has documentation on all the C# operators at:

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


EDIT - Jon B commented that a relevant quote from the linked documentation would be useful.

| is the Logical OR operator.

Binary | operators are predefined for the integral types and bool. For integral types, | computes the bitwise OR of its operands. For bool operands, | computes the logical OR of its operands; that is, the result is false if and only if both its operands are false.

^ is the Logical 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.


they are logical bitwise operators

| is a Or link

^ is XOR link


With integral types, | is a bitwise or, ^ a bitwise xor and for completeness & is a bitwise and.

With boolean types, | is a boolean or, ^ a boolean xor and & a boolean &.

In comparison, || is a short-circuit boolean or - if the first operand evaluates as true the second operand isn't evaluated. && is a short-circuit boolean and - if the first operand is false, the second isn't evaluated. There is no short-circuit ^ because there is no case where the second need not be evaluated.

|| and && are more often used than | and & in boolean cases as there is normally at least a tiny efficiency gain and never a loss. However if the right-hand operand had a side-effect that it was important to trigger in all cases, then | or & would be the one to use. In practice this is rare, and a bad smell (if the side-effect is important, it should be evaluated in a separate expression to make the purpose clearer).

Edit: A source of potential confusion, is that in some other languages integral types can be used as booleans (e.g. you can do if(53) and it's the same as if(true)) this makes the distinctions between the above operators quite different: They're the same if a "purely" boolean type is used (that has only true and false as its possible values) but not otherwise. C# deliberately doesn't allow boolean operations on integral types precisely to prevent the possibilities for mistakes that exist in such languages.