In c# programming language, The Bitwise Operators will work on bits(0,1), and these are useful to perform bit by bit operations such as Bitwise AND (&), Bitwise OR (|), Bitwise Exclusive OR (^), something like that. on operands. You can perform bit-level operations on Boolean and integer data.
For example, in given below, You have integer variables a = 10, b = 20, and the binary format of these variables is given below.
a = 10 (00001010)
b = 20 (00010100)
When you apply the Bitwise OR (|) operator on these parameters, you will get the result as given below.
00001010
00010100
-----------
00011110 = 30 (Decimal)
In the given table lists the different types of operators available in c# bitwise operators.
Operator | Name | Description | Example (a = 0, b = 1) |
& | Bitwise AND | It compares each bit of the first operand with the corresponding bit of its second operand. If both bits are 1, then the result bit will be 1; otherwise, the result will be 0. | a & b (0) |
| | Bitwise OR | It compares each bit of the first operand with the corresponding bit of its second operand. If either of the bit is 1, then the result bit will be 1; otherwise, the result will be 0. | a | b 1) |
^ | Bitwise Exclusive OR (XOR) | It compares each bit of the first operand with the corresponding bit of its second operand. If one bit is 0 and the other bit is 1, then the result bit will be 1; otherwise, the result will be 0. | a ^ b (1) |
~ | Bitwise Complement | It operates on only one operand, and it will invert each bit of operand. It will change bit 1 to 0 and vice versa. | ~(a) (1) |
<< | Bitwise Left Shift) | It shifts the number to the left based on the specified number of bits. The zeroes will be added to the least significant bits. | b << 2 (100) |
>> | Bitwise Right Shift | It shifts the number to the right based on the specified number of bits. The zeroes will be added to the least significant bits. | b >> 2 (001) |
C# Bitwise Operators Code Example
using System;
namespace FindAndSolve
{
public class Program
{
public static void Main(string[] args)
{
int a = 5, b = 10, result;
result = a & b;
Console.WriteLine("Bitwise AND: " + result);
result = a | b;
Console.WriteLine("Bitwise OR: " + result);
result = a ^b;
Console.WriteLine("Bitwise XOR: " + result);
result = ~a;
Console.WriteLine("Bitwise Complement: " + result);
result = a << 2;
Console.WriteLine("Bitwise Left Shift: " + result);
result = a >> 2;
Console.WriteLine("Bitwise Right Shift: " + result);
}
}
}
Output
Bitwise AND: 0
Bitwise OR: 15
Bitwise XOR: 15
Bitwise Complement: -6
Bitwise Left Shift: 20
Bitwise Right Shift: 1