Recursive Program for Binary to Decimal in C++


We are given a string containing a binary number. The goal is to find the equivalent decimal number using the recursive method.

A binary number can be converted to decimal using following method-: Traverse from LSB to MSB and multiply each with power of 2i Where 0<=i<=no. of digits and all previous results to it.

Let us see various input output scenarios for this −

Input − binStr[] = "110010"

Output − Equivalent Decimal of given binary: 50

Explanation−If we convert 110010 to decimal then number will be:-

= 0*20 +1*21+0*22+0*23+1*24+1*25

= 0+2+0+0+16+32

= 50

Input − binStr[] = "0011"

Output − Equivalent Decimal of given binary: 3

Explanation − If we convert 110010 to decimal then number will be:-

= 1*20+1*21 +0*22 +0*23

= 1+2+0+0

= 3

Approach used in the below program is as follows

In this approach we are using the recursive function bintoDecimal(strBin,length) which takes input string and its length and for each character convert it to decimal and multiply it with 2i . Add previous results to it.

  • Take the input string strBin[] containing a binary number.

  • Calculate its length using strlen(strBin).

  • Function bintoDecimal(strBin,length) takes input and returns the number calculated using a recursive approach.

  • If we are at last characterwhich is LSB, then return its decimal as it will be the same. (multiplied with 1 i.e 20 )

  • Otherwise set temp=binary[i]-'0'. Its decimal value.

  • Now multiply temp with 2len-i-1 using temp<<len-i-1.

  • Add the result of other digits to temp using temp=temp+bintoDecimal(binary,len,i+1).

  • At the end of recursion return temp.

  • Print the calculated decimal in main.

Example

#include<bits/stdc++.h>
using namespace std;
int bintoDecimal(char binary[],int len, int i=0){
   if (i == len-1)
   return (binary[i] - '0');

   int temp=binary[i]-'0';
   temp=temp<<len-i-1;
   temp=temp+bintoDecimal(binary,len,i+1);
   return (temp);
}
int main(){
   char strBin[] = "11010";
   int length=strlen(strBin);
   cout <<"Equivalent Decimal of given binary: "<<bintoDecimal(strBin,length) << endl;
   return 0;
}

Output

If we run the above code it will generate the following Output

Equivalent Decimal of given binary: 26

Updated on: 03-Nov-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements