
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Multiply any Number with using Bitwise Operator in C++
In this tutorial, we are going write a program that multiplies the given two numbers using bitwise operators.
The left shift (<<) operator is used for the multiplication whereas the right shift (>>) is used for the division.
The multiplication of two numbers x, y can be written as x * y = (x * 2) * (y / 2) if y is even else it's equal to x * y = (x * y) * (y / 2) + x.
So whenever the second number becomes odd, add the first number to the result. Let's see the steps to solve the problem.
Algorithm
- Initialise two numbers.
- Write a loop that iterates till the second number becomes 0.
- If the second number is odd, then add the first number to the result.
- Left shift first number by 1 bit.
- Right shift second number by 1 bit.
Implementation
Following is the implementation of the above algorithm in C++
#include <bits/stdc++.h> using namespace std; int multiplyTwoNumbers(int a, int b) { int result = 0; while (b > 0) { if (b & 1) { result += a; } a = a << 1; b = b >> 1; } return result; } int main() { cout << multiplyTwoNumbers(75, 4) << endl; cout << multiplyTwoNumbers(90, 9) << endl; cout << multiplyTwoNumbers(83, 66) << endl; return 0; }
Output
If you run the above code, then you will get the following result.
300 810 5478
- Related Articles
- Swapping numbers using bitwise operator in C
- How to multiply a given number by 2 using Bitwise Operators in C#?
- Maximum of four numbers without using conditional or bitwise operator in C++
- Bitwise NOT Operator in Golang
- Number of pairs with Bitwise OR as Odd number in C++
- Count pairs with Bitwise AND as ODD number in C++
- Count pairs with Bitwise-AND as even number in C++
- Count pairs with Bitwise OR as Even number in C++
- Count pairs with Bitwise XOR as EVEN number in C++
- Count pairs with Bitwise XOR as ODD number in C++
- What is Bitwise AND Operator (&) in JavaScript?
- What is Bitwise NOT Operator (~) in JavaScript?
- What is Bitwise OR Operator (|) in JavaScript?
- What is Bitwise XOR Operator (^) in JavaScript?
- Bitwise right shift operator in Java\n

Advertisements