Team LiB
Previous Section Next Section

Bitwise Operators

Bitwise operators allow you to evaluate the bits of a value directly. There are six operators that you can use to work with bits: AND, OR, XOR, NOT, shift left, and shift right. This section describes the AND, OR, XOR, and NOT operators. The shift operators are described in the next section. Only the NOT operator is unary, the other bitwise operators are binary.

AND (&)

The bitwise AND (&) compares every bit of each operand. If the bit in the same position of each operand is one, the resulting bit is one. However, if either bit in the same position is zero, the resulting bit is set to zero.

OR (|)

The bitwise OR (|) is also referred to as the inclusive OR operator. The bitwise OR operator works similarly to the AND operator in that it evaluates the bit in the same position. The difference is that if either bit is set to one, the result is a one; otherwise, it results in the bit being set to zero.

XOR (^)

The second type of the OR operator is the exclusive OR (^), which is also referred to as the XOR operator. This operator compares each bit and creates a resulting bit. If it is in the same position, the bit is set to 0, and the other operand bit is set to 1, the result is that the bit is set to 1; otherwise, it is set to zero.

NOT (!)

The bitwise NOT (!) is also called the complement operator. This operator is used to reverse the bit setting of the operand. So, if a bit is set to one, the bit is set to zero and vice versa.

The following is an example of using bitwise operators.

Code Example: Bitwise Operators
Start example

using System;

namespace Client.Chapter_2___ Expressions_and_Operators
{
      class BitwiseOperators
      {
            static void Main(string[] args)
            {
                  long MyBit = 0x1;
                  long MyBitResult = 0;
                  MyBitResult = MyBit & 0x1;
                  MyBitResult = MyBit | 0x2;
                  MyBitResult = MyBit ^ 0x4;
            }
      }
}
End example

Team LiB
Previous Section Next Section