Bitwise operators allow you to perform operations directly on the bits of the operands. Instead of working with entire integer values, bitwise operators handle each bit of the operands separately.
C# provides several bitwise operators, each with its own specific functionality.
Operator | Symbol |
---|---|
Bitwise AND | & |
Bitwise OR | | |
Bitwise XOR | ^ |
Bitwise NOT | ~ |
Left Shift | << |
Right Shift | >> |
Types of Bitwise Operators in C#
Bitwise AND (&
)
The bitwise AND 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 bitwise OR 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 bitwise XOR operator performs a logical XOR (exclusive OR) 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 bitwise NOT operator performs a bitwise negation of its operand, inverting each bit of the operand (0s become 1s and 1s become 0s).
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 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 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