C# Bitwise Operators
Bitwise operators are used to manipulate the individual bits of integer values. These operators work on the binary representation of numbers, and they include:
Key Bitwise Operators
Example 1: Bitwise AND
// Bitwise AND Example
int a = 5; // 0101 in binary
int b = 3; // 0011 in binary
int result = a & b; // 0001 (1 in decimal)
Console.WriteLine(result);
Output:
Code Explanation: The bitwise AND operator compares the binary representation of a
(0101) and b
(0011) and returns a new value (0001), which is 1 in decimal.
Example 2: Bitwise OR
// Bitwise OR Example
int a = 5; // 0101 in binary
int b = 3; // 0011 in binary
int result = a | b; // 0111 (7 in decimal)
Console.WriteLine(result);
Output:
Code Explanation: The bitwise OR operator compares the binary values of a
and b
and sets each bit to 1 if at least one bit is 1, resulting in 0111, which is 7 in decimal.
Example 3: Bitwise XOR
// Bitwise XOR Example
int a = 5; // 0101 in binary
int b = 3; // 0011 in binary
int result = a ^ b; // 0110 (6 in decimal)
Console.WriteLine(result);
Output:
Code Explanation: The bitwise XOR operator compares the binary values of a
and b
and sets each bit to 1 if only one of the bits is 1. This results in 0110, which is 6 in decimal.
Example 4: Left Shift
// Left Shift Example
int x = 2; // 0010 in binary
int result = x << 1; // Shift bits to the left, result is 0100 (4 in decimal)
Console.WriteLine(result);
Output:
Code Explanation: The left shift operator shifts the bits of x
one position to the left, effectively multiplying the value by 2.
Example 5: Right Shift
// Right Shift Example
int x = 4; // 0100 in binary
int result = x >> 1; // Shift bits to the right, result is 0010 (2 in decimal)
Console.WriteLine(result);
Output:
Code Explanation: The right shift operator shifts the bits of x
one position to the right, effectively dividing the value by 2.
Key Takeaways
- The bitwise AND operator
&
returns a 1 only when both bits are 1. - The bitwise OR operator
|
returns a 1 when at least one bit is 1. - The bitwise XOR operator
^
returns a 1 only when one bit is 1 and the other is 0. - Left shift
<<
multiplies the value by 2, and right shift>>
divides the value by 2.