When to use "^" operator - c#

What is the operator below ^?
When to use it?
My programing language is C#.

^ 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

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.

http://msdn.microsoft.com/en-us/library/zkacc7k1(VS.71).aspx

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

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.

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.

Related

What in the world does a ^= operator do?

I am looking at a permutation code and trying to understand how it does what it does, but one operation has me at a loss: ^=. Google will not let me search these characters, so can anyone tell me what it's doing, what does this operator mean? You can see an example of it below. Thank you!
private void swap(ref char a, ref char b)
{
if (a == b)
return;
a ^= b;
b ^= a;
a ^= b;
}
From MSDN:
An expression of the form
x ^= y
is evaluated as
x = x ^ y
except that x is only evaluated once. So, if your x is a property, it will be called once to get and once to set the value.
The ^ (XOR) operator performs a bitwise exclusive-OR operation on integral operands and logical exclusive-OR on bool operands (sum on modulus 2):
false ^ false = false;
false ^ true = true;
true ^ false = true;
true ^ true = false;
XOR operator is quite useful in cryptography as the main it's property is that
a ^ b ^ a == b;
So your code is simply add the values for a two variables so they are swaped.
a ^= b stores in a the value of a^b, which is the exclusive-or of a and b.
It's the exclusive-OR assignment operator.
You can learn more here:https://msdn.microsoft.com/en-us/library/0zbsw2z6.aspx
The exclusive-OR assignment operator.
https://msdn.microsoft.com/en-us/library/0zbsw2z6.aspx

Converting Unityscript to C#: what does something like if(format & 2) mean?

The variable 'format' is a byte and the javascript reads like:
if( format & 2 ) // have normals
{
var normals = new Vector3[vertCount];
ReadVector3ArrayBytes (normals, buf);
mesh.normals = normals;
}
Source here: http://wiki.unity3d.com/index.php?title=MeshSerializer2
C# complains about this and says it cannot implicitly convert an int to a bool.
What does format & 2 accomplish and what should I be checking for in C# to evaluate if it's true? Also some further reading material on the matter would be helpful..
The & operator in Javascript is the bitwise and operator (ref: bitwise operators).
A bitwise and operation with 2 will give the value 0 or 2 depending on whether the second bit was set in the other operand. Example:
format 01101010
2 00000010
& ----------------
= 00000010
In Javascript you can use any value as a condition in an if statement, and it will be interpreted as a boolean value. For numeric values any non-zero (and not NaN) value will be considered as true.
In C# the & operator also works as a bitwise and operator when applied to integers. There is no automatic conversion to a boolean value, so you have to check the result of the bitwise operation to get a condition:
if ((format & 2) != 0)
I think it is bit-wise operation which checks is set the second bit of byte. (2 isn't number of bit, just 10 is 2 in base 2).
if((format & 2) != 0)
{
..
}
or
if((format & 2) == 2)
{
..
}
The & is used for bitwise and operations.
The | is used for bitwise or operations.
You can only use these on integers.
Simple example to get you to understand it:
var r : int;
r = Random.Range(0, 1000);
if(r & 1)
// Odd.
else
// Even.

Applying bitwise or operator to decimal in c#

In this code, I have a requirement like below:
decimal col;
if (condition)
{
(decimal)col = (decimal)col | ((decimal)System.Math.Pow(2, 0));
}
When this code is compiled, I get an error saying
Operator | cannot be applied to operands of type 'decimal' and 'decimal'
Can anyone explain, please? Thanks
Big numbers
As the compile-time-error says, you cannot use | on decimal. The decimal type is for numbers like 12.34. If you're only using numbers like 12 or 34 then you may be better off using int (between ±2 billion) or long (between ±9 quintillion) depending how big your integer is.
Any number raised to the power zero, n0 equals 1 so your Math.Pow(2, 0) can be replaced by 1.
Your code could then look like this, which will compile.
int col;
and
if (condition)
col = col | 1;
Finally, you may prefer to use the ternary operator ?: to in-line your if statement, do whichever is more readable in your situation:
col = condition ? (col | 1) : col;
Really big numbers
Using .Net 4.0 or above
If you need to use REALLY BIG integers, there is a class for that! System.Numerics.BigInteger (in System.Numerics.dll).
The BigInteger type is an immutable type that represents an arbitrarily large integer whose value in theory has no upper or lower bounds.
Your declaration would then become:
BigInteger col;
And your bitwise operations as normal.
Using .Net 2.0 or above
Check out the project IntX
IntX is an arbitrary precision integers library written in pure C# 2.0 with fast - about O(N * log N) - multiplication/division algorithms implementation. It provides all the basic arithmetic operations on integers, comparing, bitwise shifting etc.
Reference: Big integers in C#
Cast it to Int64 then apply | operator.
decimal d1 = ..;
decimal d2 = ..;
var res = (long)d1 | (long)d2;

C# Bitwise Operator With Ints

What does this expression actually mean??
Note - the x and y vars are just sample values.
int x = 3;
int y = 1;
if ((x & y) !=0)
I inherited a codebase and am not up to speed on bitwise operators. I have read up, but am still missing something. Help!
It's comparing the bits in each value. It returns any bits that are set in both numbers.
In your example:
3: 0011
1: 0001
3 & 1: 0001
This checks whether x and y both have at least one common bit set. In the case of your example this would be the true.
if ((x & y) != 0)
This would typically be used to determine whether the value x has a specific bit-flag (y) set. The AND operator returns an integer with only those bits set that are set in both operands.

C# compound assignment operator ^=

What does this operator ^= mean in c#?
It means bitwise XOR the value of the LHS expression with the value of the RHS expression, and assign it back to the LHS expression.
So for example:
int x = 10;
int y = 3;
x ^= y; // x = 10 ^ 3, i.e. 9
The LHS expression is only evaluated once, so if you have:
array[GetIndex()] ^= 10;
that would only call GetIndex once. But please don't do that, 'cos it's nasty :)
See also the relevant MSDN page.
You may also find Eric Lippert's recent April Fool's Day blog post on compound assignment operators amusing - and part one of the series, which was rather more serious, may prove enlightening.
this:
x ^= y;
is equivalent to this:
x = x ^ y;
In words, set x to the value of x exclusive or'ed with y.
The exclusive-OR assignment operator.
An expression of the form
x ^= y
is evaluated as
x = x ^ y
except that x is only evaluated once. The ^ operator performs a bitwise exclusive-OR operation on integral operands and logical exclusive-OR on bool operands.
http://msdn.microsoft.com/en-us/library/0zbsw2z6.aspx
This is the "exclusive or assignment" operator. Details are at http://msdn.microsoft.com/en-us/library/0zbsw2z6(v=VS.100).aspx
XOR. a ^= b is the same as a = a ^ b, where a and b are integer types of some sort.

Categories

Resources