×

Binary to Decimal in C++

We must create a software to convert a binary number into an equivalent decimal value given a binary number as input.

Example:

// C++ program to convert binary to decimal
#include < iostream >
#include < bits/sdtc++.h >
#include < stdlib >
using namespace std; 
// Function to convert binary to decimal
int BinaryToDecimal ( int n )
{
	int number = n ;
	int decimal_value = 0 ; 
	// Initializing base value to 1, i.e 2^0
	int base = 1 ; 
	int temp = number ;
	while ( temp ) {
		int last_digit = temp % 10 ;
		temp = temp / 10 ; 
		decimal_value += last_digit * base ; 
		base = base * 2 ;
	}
	return decimal_value ;
}
// Driver program to test above function
int main ( )
{
	int number = 111 ; 
	cout << BinaryToDecimal ( num ) << endl ;
}

OUTPUT:

7

Explanation:

The goal is to extract the digits of a binary number starting with the rightmost digit and store them in a variable called decimal value. Multiply the digit with the suitable base (Power of 2) and add it to the variable decimal value when extracting digits from the binary integer. Finally, the decimal number will be stored in the variable decimal value. If the binary number is 111, decimal value equals 1*(2^2) + 1*(2^1) + 1*(2^0) which is equal to 7.

NOTE: The software only accepts binary values in the integer range. If you need to work with lengthy binary integers, such as 20 bits or 30 bits, you can store them in a string variable.

Storing binary values in string variables rather than integers

For example:

// C++ program to convert binary to decimal
// when input is represented as binary string.
#include < iostream >
#include < string >
#include < bits/sdtc++.h >
#include < stdlib >
using namespace std ; 
// Function to convert binary to decimal
int BinaryToDecimal ( string num )
{
	string number = num ;
	int decimal_value = 0 ; 
	// Initializing base value to 1, i.e 2 ^ 0
	int base = 1 ; 
	int length = num.length ( ) ;
	for ( int i = length - 1 ; i >= 0 ; i-- ) {
		if ( number [ i ] == '1' )
			decimal_value += base ;
		base = base * 2 ;
	}


	return decimal_value ;
}
// Driver program to test above function
int main ( )
{
	string number = "111" ;
	cout << BinaryToDecimal ( number ) << endl ;
}

OUTPUT:

7

Explanation:

In the above program it is using string to store the binary number i.e. 111 in the string number, and performing the same function as we did in the program using integer to store the binary number.

Using Pre-Defined Function

//C++ program to convert binary to decimal 
//using pre defined function
#include < iostream >
#include < bits/stdc++.h >
#include < stdlib >
using namespace std ; 
int main ( )
{
	char BinaryNumber [ ] = "111" ; 
	cout << stoi ( BinaryNumber , 0 , 2 ) ; 
	return 0 ;
}

OUTPUT:

7

Explanation:

In the above program, stoi function is a predefined function in C++, which helps in converting binary to decimal number in C++;

Another Example:

// C++ program to convert binary to decimal
#include < iostream >
#include < bits/stdc++.h >
#include < cmath >
using namespace std ; 
// function prototype
int Binarytodecimal ( long long ) ; 
int main ( ) {
  long long numver ;
  cout << "enter a binary number: " ;
  cin >> number ;
  cout << number << " in binary = " << Binarytodecimal ( number ) << " in decimal" ;
  return 0 ;
}
// function definition
int Binarytodecimal ( long long number ) {
  int decimal = 0 , i = 0 , remainder ; 
  while ( number != 0 ) {
    remainder = number % 10 ;
    number /= 10 ;
    decimal += rem * pow (2 , i ) ;
    ++i ;
  }
  return decimal ;
}

OUTPUT:

Enter a binary number: 111
111 in binary = 7 in decimal
……………………………………….
Process executed in 0.11 seconds
Press any key to continue.

Explanation:

The header file cmath has been included in the program to conduct mathematical calculations. We ask the user to provide a binary number that will be converted to decimal using the Binarytodecimcal ( ) method.

Let’s look at another example to properly understand the concept:

#include <iostream>
#include <cmath>
using namespace std;
long long Binarytodecimal (int); 
int main() {
  int n, bin;
  cout << "enter a decimal number: ";
  cin >> n;
  bin = Binarytodecimal(n);
  cout << n << " in decimal = " << bin << " in binary" << endl ;
  return 0;
}
long long Binarytodecimal(int n) {
  long long bin = 0;
  int rem, i = 1; 
  while (n!=0) {
    rem = n % 2;
    n /= 2;
    bin += rem * i;
    i *= 10;
  }
  return bin;
}

OUTPUT:

Enter a decimal number: 10
10 in decimal = 1010 in binary

Explanation:

In this above program we are using a while loop for our iteration in the function called Binarytodecimal.


Related Topics

Returning Multiple Values from a Function using Tuple and Pair in C++

We may come across many situations where after the driver code's execution is performed in a code block, the return should be either multiple values or a single value possibly...

4 minutes read.

Object Slicing in C++

In this article, we will learn about Object slicing. When an object from a derived class is assigned to an object from a base class in C++, these extra attributes...

3 minutes read.

Pattern programs in C++

In this article, we are going to discuss different pattern programs in C++. Program for Printing * patterns: Right Angle Triangle* pattern #include <iostream> using namespace std; int main() {     int rows;     cout <<...

3 minutes read.

C++ array of Pointers

Array of Pointers: In high-level programming languages like C++, the array's name is its pointer. The name of an array contains an address which is the address of an element. In...

4 minutes read.

C++ STL Components

C++ STL Components In today’s article, we are going to learn about all the points things that is related to STL in C++ so stay connected because you are going to...

6 minutes read.

Exception Handling in C++ vs Java

Nowadays, exception handling is a feature found in virtually all object-oriented languages. We can also find this type of feature in Java and C++. The try-catch and block is required...

3 minutes read.

Top 14 Best Free C++ IDE (Editor & Compiler) for Windows in 2024

Bjarne Stroustrup created the all-purpose object-oriented programming language C++. To develop C++ programs, there are various Integrated Development Environments (IDE) that offer prewritten code templates. These programs automatically modify the...

6 minutes read.

Ascending order in C++

In C++, the term "ascending order" refers to a specific order in which a list of elements is arranged. When a list of elements is arranged in ascending order, the...

3 minutes read.

Parameterize Constructor

C++ Parameterized Constructor A constructor having parameters is known as parameterize constructor. Parameterize constructor is used to assign different values. Syntax: className(data-type argument){   // Constructor definition   }   className(data-type argument, data-type argument){   // Constructor definition   } A parameterized constructor can be passed values to constructor function in two ways: 1)...

1 minute read.

C++ Bidirectional Iterators

Iterators : Iterators serve as a link between algorithms and STL containers, allowing the data inside the container to be modified. They let you to iterate through the container, access and...

3 minutes read.

How to improve programming skills in C++

Before getting started, one should know why to improve their programming skills. To become a good software developer or programmer, one must be skilled in at least one programming language. Many...

4 minutes read.

C++ Program: Matrix Multiplication

Matrix Multiplication in C++ What is a Matrix? A matrix is a set of numbers in the form of rows and columns forming a rectangular array. It includes numbers, which are often...

4 minutes read.

fscanf() Function in the C++

In the C++ programming language, the fscanf() method can be used to read data from a file stream. Syntax: The syntax for the fscanf() function in the C++ programming language is as...

3 minutes read.

Initialize Vector in C++

Initialize Vector in C++  The following comparison operators are defined for vector and those are given below. ==, <, <=, !=, >,>=  This allows you to access the element of a vector using...

3 minutes read.

C++ Fibonacci Series

What is a Fibonacci series? A Fibonacci series or sequence is a very popular programming paradigm. The next element occurring in the N terms series is determined by the sum of...

2 minutes read.

While Loop Examples in C++

While Loop A while loop repeats all code in its body, also known as a while statement, as long as a specific condition is satisfied. The loop ends if or when...

4 minutes read.

C++ Overloading

C++ Overloading is a condition when two or more members have the same name with different parameter type or a different number of parameter. C++ overloading is two types: Function...

1 minute read.

Lambda Expression in C++

The lambda expression was introduced in C++ 11. It is used to write the inline function in C++. The code written in lambda expression cannot be reused further. The syntax...

3 minutes read.

How to concatenate two strings in C++

In the C++ programming language, the concatenation of two or even more strings is covered in this section. The term "string concatenation" refers to a collection of characters that join two...

4 minutes read.

Dynamic Binding in C++

The notion of dynamic binding solved the challenges associated with static binding. Static binding refers to bindings that can be resolved by the compiler at runtime. All storage, stationary, and...

3 minutes read.