C# Bitwise Operators

The C# Bitwise operators only applied to numbers. Before these operators work on the given input(number), the system converts that number from decimal to binary. And then, the bitwise operator performs its action on bits(binary). And then finally, the result is displayed for us in decimal form after converting bits into decimal.

Input(decimal) ->(decimal to binary) -> C# bitwise operators perform the necessary action on bits -> Bits converted to decimal -> result is displayed in decimal form.

OperationExample
& Bitwise AND16 & 10 =0
| Bitwise OR16 | 10 =26
~ Bitwise Complement~16= -17
^ Exclusive OR16 ^ 10=26

Let us see the truth table for these C# bitwise operators.

Xyx & yx | yx ^ y
00000
01011
10011
11110

C# Bitwise Operators Example

The following example shows you the working functionality of all the bitwise operators.

using System;
 
class Bitwise_Operators
{
   static void Main()
   {
     int x = 16;
     int y = 10;
     int result;
 
     result = ~x;
     Console.WriteLine("~{0} is {1}", x, result);
 
     result = x & y;
     Console.WriteLine("{0} & {1} = {2}", x, y, result);

     result = x | y;
     Console.WriteLine("{0} | {1} = {2}", x, y, result);
 

     result = x ^ y;
     Console.WriteLine("{0} ^ {1} = {2}", x, y, result);
   }
}
C# Bitwise Operators Example

x = 16 and y = 10

The C# Bitwise operations were performed as follows:

First, 16 and 10 are converted into bits and the binary form of 16 is 10000, and 10 is 1010.

~(16) is -17, which is the two’s complement of 16.

10000 & 01010 is 00000 – The result is 0

10000 | 01010 is 11010 – The decimal form of 11010 is 26

10000 ^ 01010 is 11010 – The decimal form of 11010 is 26

C# Shift Operators

The C# Bitwise Shift operators move bit positions. It means bit positions of the left operand are shifted to either left or right, number of positions specified in the right operand. C# enables a bit shifting with the right shift (>>) and left shift (<<) operators.

Shift OperatorsOperationExample
>>Right Shift Operation16 >> 3 is
<<Left Shift Operation16 << 2

Let us see an example code using these Bitwise shift operators.

Bitwise Left and Right Shift Operators Example

using System;
 
 class Shift_Operators
 {
     static void Main()
     {
         int x = 16;
         int result;
 
         result = x >> 3;
         Console.WriteLine("{0} >> 3 is {1}", x, result);
 
         result = x << 2;
         Console.WriteLine("{0} << 2 is {1}", x, result);
     }
 }

OUTPUT

16 >> 3 is 2
16 << 2 is 64

In the above code

16 >> 3, The binary form of 16 is 0001 0000

10000 is shifted three digits towards the right, i.e., 0000 0010, whose decimal value is 2.

16 << 2, After shifting the binary form of 16, i.e., 0001 0000, by 2 digits towards the left, the result is 0100 0000, whose decimal form is 64.

Categories C#