Hi,
I'm having some trouble with my code that convert binary to decimal using recursion. this is my code

#include <cstdlib>
#include <iostream>
using namespace std;
void binaryToDecimal( int binaryNumber, int decimal, int weight );
int main(int argc, char *argv[])
{
   // binary to decimal 
    int decimalNum;
    int bitWeight;
    int binaryNum;
    decimalNum = 0;
    bitWeight = 0;
    cout <<"enter a number in binary: ";
    cin >> binaryNum;
    cout << endl;
    binaryToDecimal(binaryNum, decimalNum, bitWeight);
    cout << "Binary" << binaryNum << "=" << decimalNum
         <<"decimal" << endl;

    system("PAUSE");
    return EXIT_SUCCESS;
}

void binaryToDecimal( int binaryNumber, int decimal, int weight )
{
     int bit;
     if ( binaryNumber > 0 )
     bit = binaryNumber % 10;
     decimal = decimal + bit * pow(2, weight );
     binaryNumber = binaryNumber / 10;
     weight++;
     binaryToDecimal(binaryNumber, decimal, weight );
}

my teacher said that i have to do the following errors, but I have no idea how to fix it..

1 - the binaryNumber variable should be a string, not an int, example: "110110"
2 - the function should return an int, the binary string converted to a decimal number
3 - your function never returns, i.e. never stops, that is the cause of the crash

Can someone please help me.
thanks,:)

Dani AI

Generated

A simple way to meet your teacher’s requirements is to recurse over the binary string from left to right, carrying the partial decimal value as an accumulator. This avoids floating-point pow, avoids globals/statics (see notes to and @Mr. K below), and guarantees termination with a clear base case.

#include <string>
#include <stdexcept>

int binToDec(const std::string& bits, std::size_t i = 0, int acc = 0) {
    if (i == bits.size()) return acc;                 // base case: done
    char c = bits[i];
    if (c != '0' && c != '1')                         // validate input
        throw std::invalid_argument("non-binary digit");
    return binToDec(bits, i + 1, (acc << 1) + (c - '0'));  // shift + add bit
}

// usage:
// std::string s; std::cin >> s;
// int value = binToDec(s);

How it works:

  • Each step consumes one character. Shifting acc left by 1 multiplies by 2; adding the current bit incorporates it.
  • The recursion stops when i == bits.size(), returning the accumulated value.
  • Using a std::string preserves leading zeros and lets you reject invalid digits early. If you expect very long inputs, change the return type to long long or wider to avoid overflow.

Notes on earlier replies:

  • The pow(2, weight) approach shown by and @Mr. K mixes floating point with integers and invites rounding errors; the bit-shift is exact and faster.
  • Relying on a global or static sum (as suggested later) couples state to the function and breaks reentrancy. Passing acc as a parameter keeps the function pure and testable.
  • If you prefer right-to-left recursion, you can index from the end instead, but still return the computed value rather than trying to update an external variable.

Recommended Answers

All 5 Replies

Did you bother to read any of the requested information posted all over this site about CODE tags, like
1) in the Rules you were asked to read when you registered
2) in the text at the top of this forum
3) in the announcement at the top of this forum titled Please use BB Code and Inlinecode tags
4) in the sticky post above titled Read Me: Read This Before Posting
5) any place CODE tags were used
6) on the background of the box you actually typed your message in

commented: Indeed, well said +29

//edit code of binary to decimal conversion(using recursive function)
//try it,,,its working

#include <iostream>
#include <math.h>

int sum=0;
using namespace std;
int binaryToDecimal( int binaryNumber, int weight );
int main()
{
// binary to decimal

int bitWeight;
int binaryNum;
bitWeight = 0;
cout <<"enter a number in binary: ";
cin >> binaryNum;
cout << endl;
int sum=binaryToDecimal(binaryNum, bitWeight);
cout << "Binary " << binaryNum << "= "<< sum<< endl;

system("PAUSE");
return 0;
}

int binaryToDecimal( int binaryNumber, int weight )
{
int bit;
if ( binaryNumber> 0 ){
bit = binaryNumber % 10;
sum = sum + bit * pow(2, weight );
binaryNumber = binaryNumber / 10;
weight++;
binaryToDecimal(binaryNumber, weight );}
return sum;
}

Hi,
I'm having some trouble with my code that convert binary to decimal using recursion. this is my code

#include <cstdlib>
#include <iostream>
using namespace std;
void binaryToDecimal( int binaryNumber, int decimal, int weight );
int main(int argc, char *argv[])
{
   // binary to decimal 
    int decimalNum;
    int bitWeight;
    int binaryNum;
    decimalNum = 0;
    bitWeight = 0;
    cout <<"enter a number in binary: ";
    cin >> binaryNum;
    cout << endl;
    binaryToDecimal(binaryNum, decimalNum, bitWeight);
    cout << "Binary" << binaryNum << "=" << decimalNum
         <<"decimal" << endl;

    system("PAUSE");
    return EXIT_SUCCESS;
}

void binaryToDecimal( int binaryNumber, int decimal, int weight )
{
     int bit;
     if ( binaryNumber > 0 )
     bit = binaryNumber % 10;
     decimal = decimal + bit * pow(2, weight );
     binaryNumber = binaryNumber / 10;
     weight++;
     binaryToDecimal(binaryNumber, decimal, weight );
}

my teacher said that i have to do the following errors, but I have no idea how to fix it..
1) the binaryNumber variable should be a string, not an int
example: "110110"
2) the function should return an int, the binary string converted to a decimal number
3) your function never returns, i.e. never stops, that is the cause of the crash

Can someone please help me.
thanks,:)

see below..i have modify your code..now its working...just copy and paste..and enjoy it...dont forget to reply..

Did you find any error? What type of error did you get?

#include <iostream>
#include <math.h>

int sum = 0;
using namespace std;
int binaryToDecimal( int binaryNumber, int weight );
int main()
{
// binary to decimal

int bitWeight;
int binaryNum;
bitWeight = 0;
cout <<"enter a number in binary: ";
cin >> binaryNum;
cout << endl;
int sum = binaryToDecimal(binaryNum, bitWeight);
cout << "Binary " << binaryNum << "= "<< sum<< endl;

system("PAUSE");
return 0;
}

int binaryToDecimal( int binaryNumber, int weight )
{
int bit;
if ( binaryNumber > 0 ){
bit = binaryNumber % 10;
sum = sum + bit * pow(2, weight );
binaryNumber = binaryNumber / 10;
weight++;
binaryToDecimal(binaryNumber, weight );
}
return sum;
}

There is one mistake in code mentioned by Mr. K. In BinaryToDecimal function, sum should be static variable else value will not be retained. You are adding to a garbage value.

So I think it should be:

  int binaryToDecimal( int binaryNumber, int weight )
    {
    int bit;
    static int sum = 0;
    if ( binaryNumber > 0 ){
    bit = binaryNumber % 10;
    sum = sum + bit * pow(2, weight );
    .
    .
    .
    .
    }
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.