Index Books FAQ Contact About Rod

# Title: Use bit operations in C#

C# defines several operators that perform bit operations. As you may be able to guess from the names, these operators manipulate the bits in an integer value. They operate on the value's bits separately so they are sometimes called "bitwise operators."

The following tables describes the bit operations and their operators.

OperatorNameMeaning
~NotFlips each bit so a 1 becomes a 0 and vice versa. (This is also called "bitwise negation.")
|OrA bit becomes 1 if it is a 1 in either of its two operands. If A and B are integers, then a bit in A | B is 1 if the corresponding bit in A or B is 1.
&AndA bit becomes 1 if it is a 1 in both of the two operands. If A and B are integers, then a bit in A & B is 1 if the corresponding bit in A and B are both 1.
^XorA bit becomes 1 if it is a 1 in one but not both of the two operands. If A and B are integers, then a bit in A ^ B is 1 if exactly one of the corresponding bits in A and B is 1. (This operator is called the "exclusive or.")
<<Left shiftThe bits in the single operand are moved to the left. Bits that drop off the left end of the number are discarded. New bits on the right are always set to 0. For example, 11100111 << 2 gives 10011100.
>>Right shiftThe bits in the single operand are moved to the right. Bits that drop off the right end of the number are discarded. New bits on the left repeat the number's original leftmost bit. For example, 11001100 >> 2 gives 11110011 and 00110011 >> 2 gives 00001100.

Take a few minutes to work through the examples displayed by the program to make sure you understand how each operator works.

The bit operations that take two operands (all of them except ~) also have compound assignment versions. For example, A ^= B is equivalent to A = A ^ B and A <<= C is equivalent to A = A << C.

All of these operations are defined for all of the integral types (sbyte, byte, char, short, ushort, int, uint, long, ulong), but the shorter data types are promoted to integers when the operations executes. For example, if short_a and short_b are short integers, then short_a ^ short_b returns an int. If you want to store the result in a short, you need to cast it into a short as in short_c = (short)(short_a ^ short_b).