Bitwise Operators October, 2006
The following is a breakdown of 4 basic bitwise operators; NOT, OR, XOR and AND.
NOT
NOT produces the inverse of a binary value. For example:
1 will be 0 and 0 will be one. In C# NOT operations are only allowed on Boolean values. The NOT operator is an exclamation point (!).
bool i = true;
Console.WriteLine(!i);
// returns false
OR
OR produces a 1 if either corresponding bit is 1. This means that if both are one or if only one is 1 the result is 1. If both are zero then the result is zero. For example:
In C# the OR operator is the pipe (|).
int i = 23; // 010111
int z = 45; // 101101
Console.WriteLine(i | z);
// 63 - 111111
XOR
XOR (Or Exclusive OR) produces a 1 if either corresponding bit is 1 but not both, in other words mutually exclusive. This means that 1 and 0 or 0 and 1 will be 1. 0 and 0, 1 and 1 will produce 0. For example:
In C# the XOR operator is the caret (^).
int i = 23; // 010111
int z = 45; // 101101
Console.WriteLine(i ^ z);
// 58 - 111010
AND
AND produces a 1 only if both corresponding bits are 1, otherwise it produces a 0. For example:
In C# the AND operator is the ampersand (&).
int i = 23; // 010111
int z = 45; // 101101
Console.WriteLine(i & z);
// 5 - 000101