Binary to Decimal in C++

To Convert Binary Numbers into Decimal , we need to multiply each binary digit with Powers of 2 starting from right side.
For Example. Binary Number 100101 will be converted to Decimal using following steps
(2^5) * 1 + (2^4) * 0 + (2^3) * 0 + (2^2) * 1 + (2^1) * 0 + (2^0) * 1
Power of 2 is starting from 0 and increasing from righ to left.
= 32+0+0+4+0+1 = 37
So 100101 is Equal to 37 in Decimal System

Code for Binary to Decimal:

//Binary to decimal
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
	char arr[100];
	long int dec=0,i,j;
	cout<<"Enter binary "<<endl;
	cin>>arr;
	for(i=0;arr[i]!='\0';i++);
	for(i=i-1,j=0;i>=0;i--,j++)
	{
		dec+=(arr[j]-48)*pow(2,i);
	}
	cout<<"\nDecimal "<<dec;
}

Output:

Enter binary
100101

Decimal 37

Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *