C# Bitwise Operators Examples – Programming, Pseudocode Example, C# Programming Example
C#

C# Bitwise Operators Examples

In this post, we’ll learn Bitwise operators in C#.

In c#, Bitwise Operators will work on bits, and these are useful to perform bit by bit operations such as Bitwise AND (&), Bitwise OR (|), Bitwise Exclusive OR (^), etc. on operands. We can perform bit-level operations on Boolean and integer data.

For example, we have integer variables a = 10b = 20, and the binary format of these variables will be shown below.

a = 10 (00001010)
b = 20 (00010100)

When we apply the Bitwise OR (|) operator on these parameters, we will get the result shown below.

00001010
00010100
———–
00011110 = 30 (Decimal)

The following table lists the different types of operators available in c# bitwise operators.

OperatorNameDescriptionExample (a = 0, b = 1)
&Bitwise ANDIt 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 ORIt 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 ComplementIt 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 ShiftIt 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 Example

Following is the example of using the Bitwise Operators in the c# programming language.

If you observe the above code, we used different bitwise operators (&, |, ^, ~, <<, >>) to perform different operations on defined operands.

Output

When we execute the above c# program, we will get the result as shown below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.