How to multiply a given number by 2 using Bitwise Operators in C#?


A number can be multiplied by 2 using bitwise operators. This is done by using the left shift operator and shifting the bits left by 1. This results in double the previous number.

A program that demonstrates multiplication of a number by 2 using bitwise operators is given as follows.

Example

 Live Demo

using System;
namespace BitwiseDemo {
   class Example {
      static void Main(string[] args) {
         int num = 25, result;
         result = num << 1;
         Console.WriteLine("The original number is: {0}", num);
         Console.WriteLine("The number multiplied by two is: {0}", result);
      }
   }
}

Output

The output of the above program is as follows.

The original number is: 25
The number multiplied by two is: 50

Now let us understand the above program.

First, the number is defined. Then, the left shift operator is used and the bits in num are shifted left by 1. This results in double the previous number which is stored in result. Then, the values of num and result are displayed. The code snippet for this is given as follows −

int num = 25, result;
result = num << 1;
Console.WriteLine("The original number is: {0}", num);
Console.WriteLine("The number multiplied by two is: {0}", result);

Updated on: 27-Jun-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements