Here you will learn how to convert binary to decimal in C++.
We can convert a binary number into decimals in the following way.
- Multiply each digit from right to left by a power of 2. Here the power of 2 will be the position of the digit starting from 0.
- Now add all the values to obtain the decimal number.
Also Read: Convert Decimal to Binary in C++
C++ Program to Convert Binary to Decimal
#include<iostream>
#include<math.h>
using namespace std;
int main()
{
unsigned long i,n,num=0,d;
cout<<"Enter any Binary number:";
cin>>n;
cout<<"\nThe Decimal conversion of "<<n<<" is ";
for(i=0;n!=0;++i)
{
d=n%10;
num=(d)*(pow(2,i))+num;
n=n/10;
}
cout<<num;
return 0;
}
Output:
Enter any Binary number:111
The Decimal conversion of 111 is 7
i have seen this approach on the net many times, can u give us something new….like another method to perform this particular conversion ..
/*This is another approach, but this has a flaw while used in C++. This code works perfectly in C language.
This program uses the Algo with the least no of executable lines in C to perform the binary to decimal conversion, hence the quickest known to me. To know about the flaw or any doubt in the code U can ask me on this email id : abhishekroy.id@gmail.com*/
#include
void main()
{
long int bnum,dnum=0,base=1,rem;
cout<<"Enter the binary number : ";
cin>>bnum;
while(bnum!=0)
{
rem = bnum%10;
dnum = dnum+rem*base;
base = base*2;
bnum = bnum/10;
}
cout<<"nEquivalent decimal value : "<<dnum;
}
//cheers!!!