×

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

External merge sort in C++

External merge sort in C++ External sorting is a concept for a group of sorting algorithms capable of handling large data volumes. External sorting is needed if the information getting sorted...

9 minutes read.

C++ Socket Programming

In this world, computer networking has become very important for sharing of data. Every good programmer has some knowledge about computer networking. Socket programming is one of the critical topics...

6 minutes read.

Dynamic Constructor in C++

Dynamic constructors create dynamic memory by using a dynamic memory allocator new within the constructor. This allows us to initialize objects dynamically. The term dynamic constructor is used when memory...

2 minutes read.

Is it fine to write void main() or main() in C/C++?

In C programming language: The default function return type in the C programming language is "int," which implies that main() will always return an integer value. In C, the void main()...

3 minutes read.

CPP Templates

C++ provides a powerful feature called template, which allows the definition of generic classes and generic functions. Generic programming is a technique where different algorithms work in communion by using...

4 minutes read.

How to find the length of the vector in C++

Like dynamic arrays, vectors can automatically adjust their size when an element is added or removed, and the container manages its storage. Because vector items are stored in contiguous storage, iterators...

3 minutes read.

C++ Scope of Variables

In this tutorial, we will explore about the scope of variables in c++ programming language. And also, how it works in a program. What is Scope? The range of applications for something...

4 minutes read.

Stack in C++

Stack: The stack is a very popular data structure. It is the form of data structure that follows a particular order called FIFO(First-In-First-Out). In simple words, a stack is an Abstract...

4 minutes read.

C++ Continue

In C++, the continue statement is a useful tool for avoiding specific scenarios without breaking the loop. It is employed inside loops to move directly to the following iteration and...

4 minutes read.

C++ Pointer

Pointer is a derived data type that stores the address of a variable. A pointer is used for memory management and dynamic memory allocation. Pointer works on the address of data rather than...

2 minutes read.

Const_cast in C++ Type Casting Operators

In this tutorial, we will learn enough about const cast in the most widely used programming language, C++, as well as type casting operations. C++ supports the four types of casting...

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.

Inheritance Program in C++

What is Inheritance? Inheritance is the ability of a class to inherit traits and properties from another class. One of the most crucial aspects of Object-Oriented Programming is inheritance. The ability or...

9 minutes read.

Do-While Loop Examples in C++

Before we move on the examples of Do-While loop, let’s learn little bit about the Do-While loop in C++ language. Do While loop An iterative loop that checks the condition at the...

5 minutes read.

4 Pillars of OOPs

OOPs OOPS means Object Oriented Programming System Structure. Object oriented Programming is defined as an approach that provides a way of modularizing programs by creating partitioned memory area for both data...

11 minutes read.

C++ Type Casting

The type casting of variables in the C++ programming language will be covered in this section. The term "type casting" describes how software converts one data type to another. There...

9 minutes read.

swap() function in C++

Swap() function: swap() function in C++: swap() function is a pre-define function in c++ present in STL( Standard template library ). It is used to swap two numbers. It takes two mandatory...

6 minutes read.

Template Specialization in C++

Template is a feature of C++. With the help of a template, we can write the code only once and use that code multiple times. For example, there is a...

4 minutes read.

Pthreads or POSIX Threads in C++

The thread API for C/C++ is implemented by pthreads or POSIX threads. It enables the multithreading system, which enables parallel and distributed processing, and the creation of new concurrent process...

3 minutes read.

Processing strings using std string stream in C++

A string class object called std: string stream is used to streamline into various variables, just as files can pour into strings. This class's things make use of a string...

3 minutes read.