C# XOR Operator (Bitwise)Use the bitwise XOR operator to manipulate bits in an int variable.
Exclusive-or modifies a bit pattern. If both operands have a bit set, the result does not have that bit set. If neither has a bit set, the result also does not have that bit set. But if one has the bit set, the result is set.Binary Representation
let's look at an example program. The XOR operator is a binary operator, meaning is requires two operands. As a reminder, an operand is a numeric argument to the operator (the numbers on each side of the "^" caret symbol).
Here: In this program, we use a method that shows us the bits that are set in each number.
And: We see the bits set in the first operand, the second operand, and the result returned by the XOR operation.
Output: The first two lines are the bits of the operands. The third line is the result from the "^" operator applied to those operands.
Tip: In places where only one bit is set in both operands, the result value has that same bit set. Otherwise no bits were set.
C# program that uses XOR operator
static void Main()
// Demonstrate XOR for two integers.
int a = 5550 ^ 800;
int b = 100 ^ 33;
/// Returns binary representation string.
static string GetIntBinaryString(int n)
char b = new char;
int pos = 31;
int i = 0;
while (i < 32)
if ((n & (1 << i)) != 0)
b[pos] = '1';
b[pos] = '0';
return new string(b);
Bitwise operators are exceedingly useful in some cases, but sadly not in many programs today. Typically, if you don't have limited memory on your system, you can replace bitwise operations with arrays.Array
For some programs,
such as those that use digital trees, you can use bitwise operators to test the bit patterns at each node. This yields an efficient search tree. Bitwise operators can also be used for hash code computations.TreeGetHashCode
The XOR binary operator receives two operands, and returns a number that contains a bit set for each exclusive bit set in an operand. In many programs, this operator is more trouble than it is worth, and will likely cause confusion.
Warning: Please proceed with the XOR operator with caution. It is sometimes helpful but often not.Optimization
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to firstname.lastname@example.org.