C++ Program to Convert Binary to Decimal
Write C++ Program to Convert Binary to Decimal
// CPP Program to Convert Binary to Decimal
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
long int n, ans = 0;
cout << "Enter Binary Number :--> ";
cin >> n;
int i = 0;
while(n != 0)
{
int digit = n % 10; //here we take the last digit
if(digit == 1)
{
ans = (digit * pow(2,i)) + ans; //formula for the conversion
}
n = n / 10; // reducing the number
i++;
}
cout << "The Decimal Number is :--> " << ans;
return 0;
}
Output:
Enter Binary Number :--> 101101
The Decimal Number is :--> 45