Question #94217

Write a program to convert a number from a binary representation to a decimal format—that is, from base 2 to base 10. Your program should make use of recursion to do the conversion.

Expert's answer

#include <iostream>
#include <math.h>
using namespace std;
int bin_to_dec(long int binary, int radix, int decimal)
{
   if(binary%10)
   {
       decimal += pow(2, radix);
       binary = (binary - 1) / 10;
       radix++;
       bin_to_dec(binary, radix, decimal);
   }
   else if(binary != 0)
   {
       binary /= 10;
       radix++;
       bin_to_dec(binary, radix, decimal);
   }
   if(binary == 0)
       return decimal;
}
int main()
{
   cout<<bin_to_dec(1101001011, 0, 0)<<endl;//enter the number you ant to convert as the first argument
   return 0;
}
LATEST TUTORIALS
APPROVED BY CLIENTS