Bitwise operators in C# allow perform operations directly on the bits of the operands. Instead of working with full integer values, bitwise operators treat each bit of the operands separately.
C# provides several bitwise operators, each with its own specific functionality. Here is a summary table.
Operator | Symbol |
---|---|
Bitwise AND | & |
Bitwise OR | | |
Bitwise XOR | ^ |
Bitwise NOT | ~ |
Left Shift | << |
Right Shift | >> |
Types of bitwise operators in C#
Bitwise AND
The AND bitwise operator performs a logical AND operation between each pair of corresponding bits of two operands. The result is 1
only if both bits are 1
, otherwise the result is 0
.
int a = 12; // 1100 in binary
int b = 10; // 1010 in binary
int result = a & b; // 1000 in binary, which is 8 in decimal
Console.WriteLine(result); // Output: 8
Bitwise OR
The OR bitwise operator performs a logical OR operation between each pair of corresponding bits of two operands. The result is 1
if at least one of the bits is 1
, otherwise the result is 0
.
int a = 12; // 1100 in binary
int b = 10; // 1010 in binary
int result = a | b; // 1110 in binary, which is 14 in decimal
Console.WriteLine(result); // Output: 14
Bitwise XOR
The XOR bitwise operator performs a logical XOR (exclusive) operation between each pair of corresponding bits of two operands. The result is 1
if one and only one of the bits is 1
, otherwise the result is 0
.
int a = 12; // 1100 in binary
int b = 10; // 1010 in binary
int result = a ^ b; // 0110 in binary, which is 6 in decimal
Console.WriteLine(result); // Output: 6
Bitwise NOT
The NOT bitwise operator performs a bitwise negation of its operand, inverting each bit of the operand (the 0
s become 1
s and vice versa).
int a = 12; // 1100 in binary
int result = ~a; // 0011 in binary, which is -13 in decimal (in two's complement)
Console.WriteLine(result); // Output: -13
Left Shift
The left shift operator shifts the bits of its operand to the left by a specific number of positions, filling the empty bits on the right with zeros.
int a = 3; // 0011 in binary
int result = a << 2; // 1100 in binary, which is 12 in decimal
Console.WriteLine(result); // Output: 12
Right Shift
The right shift operator shifts the bits of its operand to the right by a specific number of positions. The empty bits on the left are filled with the sign bit (for negative numbers) or with zeros (for positive numbers).
int a = 12; // 1100 in binary
int result = a >> 2; // 0011 in binary, which is 3 in decimal
Console.WriteLine(result); // Output: 3