# C++ Decimal to Binary (Recursively)

Page 1 of 1

## 12 Replies - 9899 Views - Last Post: 31 January 2010 - 08:40 PMRate Topic: 1 Votes //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=152634&amp;s=d44676afa7709ea299a06233032357ec&md5check=' + ipb.vars['secure_hash'], cur_rating: 5, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 richbria90

Reputation: 1
• Posts: 23
• Joined: 21-January 10

# C++ Decimal to Binary (Recursively)

Posted 29 January 2010 - 12:07 AM

Alright so I'm resorting to you guys because this recursion is really ticking me off.... basically right now i'm working on Decimal to Binary and running into a problem. I looked at everyone else's code and nothing quite fit my problem... so here it is

```//Implementation File for Convert Class

#include "Convert.h"
#include <iostream>
#include <cstdlib>
using namespace std;

//Constructors
Convert::Convert()
{
decNum= 0;
binNum= "";
hexNum= "";
}
//Mutator Functions
bool Convert::setDecNum(int dec)
{
decNum = dec;
return true;
}
bool Convert::setBinNum(string bin)
{
binNum = bin;
return true;
}
bool Convert::setHexNum(string hex)
{
hexNum = hex;
return true;
}
// Accessor Functions
int Convert::getDecNum()
{
return decNum;
}
string Convert::getBinNum()
{
return binNum;
}
string Convert::getHexNum()
{
return hexNum;
}
//Utility Functions

// *****HERE is where my problem is....***

bool Convert::convDec2Bin(int needsConverted, int divisor)
{
if (needsConverted % 2 == 0)
binNum += "1";
/* if
return(convDec2Bin(needsConverted, divisor*2));
//binNum += "1";
//return (convDec2Bin(needsConverted-divisor, divisor/2));
if (needsConverted == divisor)
{
binNum += "1";
return (true);
}
if (needsConverted > divisor)
{
binNum += "1";
return (convDec2Bin(needsConverted-divisor, divisor/2));
}
else
{
binNum+= "0";
return(convDec2Bin(needsConverted, divisor/2));
}*/
}

//binNum = atoi(needsConverted.c_str());//alpha to integer
//return binNum;
string Convert::convDec2Hex(int needsConverted)
{
return hexNum;
}
int Convert::convBin2Dec(string needsConverted)
{
return decNum;
}
int Convert::convHex2Dec(string needsConverted)
{
return decNum;
}

```

The recursion is throwing me for a loop from a design standpoint I can do pretty much whatever I want so any help is greatly appreciated... my first attempt was %2 because then i just multiply that by 2 for my recursion.. but there is backtracking involved that is messing it up...

Is This A Good Question/Topic? 0

## Replies To: C++ Decimal to Binary (Recursively)

### #2 richbria90

Reputation: 1
• Posts: 23
• Joined: 21-January 10

## Re: C++ Decimal to Binary (Recursively)

Posted 29 January 2010 - 12:44 AM

Come on I know someone out there is just dieing to get into some recursion.... help me out lol....

I just need help identifying what my base cases should be... and then I'm off to see the wizard...

Reputation:

## Re: C++ Decimal to Binary (Recursively)

Posted 29 January 2010 - 01:14 AM

here is the code for converting decimal to binary:
```//Implementation File for Convert Class

#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;

//Constructors

class Convert{
int decNum;
string binNum;
string hexNum;
public:
Convert();
void setDecNum(int dec);
void setBinNum(string bin);
void setHexNum(string hex);
int getDecNum();
string getBinNum();
string getHexNum();
void convDec2Hex(int needsConverted);
void convDec2Bin(int needsConverted);
void convBin2Dec(string needsConverted);
void convHex2Dec(string needsConverted);
};

Convert::Convert()
{
decNum= 0;
binNum= "";
hexNum= "";
}
//Mutator Functions
void Convert::setDecNum(int dec)
{
decNum = dec;
}
void Convert::setBinNum(string bin)
{
binNum = bin;
}
void Convert::setHexNum(string hex)
{
hexNum = hex;
}
// Accessor Functions
int Convert::getDecNum()
{
return decNum;
}
string Convert::getBinNum()
{
return binNum;
}
string Convert::getHexNum()
{
return hexNum;
}

void Convert::convDec2Bin(int needsConverted)
{
if(needsConverted!=0)
{
if (needsConverted % 2 == 0)
{
binNum = "0" + binNum;
convDec2Bin(needsConverted/2);
}
else
{
binNum = "1" + binNum;
convDec2Bin(needsConverted/2);
}
}
else return;

}

void Convert::convDec2Hex(int needsConverted)
{
//return hexNum;
}
void Convert::convBin2Dec(string needsConverted)
{
//return decNum;
}
void Convert::convHex2Dec(string needsConverted)
{
//return decNum;
}

int _tmain(int argc, _TCHAR* argv[])
{
Convert Number = Convert();
Number.convDec2Bin(8);
cout << Number.getBinNum();
getc(stdin);
return 0;
}

```

set, get, convert functions should be void. why do you make them return bool? enhance code yourself to make dec to hex and so on

### #4 [email protected]

Reputation: 1
• Posts: 57
• Joined: 06-February 08

## Re: C++ Decimal to Binary (Recursively)

Posted 29 January 2010 - 02:22 AM

dont declare the functions set,get and convert functions as boolean type...you should declare as void..k

### #5 richbria90

Reputation: 1
• Posts: 23
• Joined: 21-January 10

## Re: C++ Decimal to Binary (Recursively)

Posted 29 January 2010 - 11:59 AM

I have to disagree with you guys on this one the set functions are type bool so when I am done coding I can prevent someone from putting in values that dont make sense ie
(if dec<0 )
return false;
else
decNum = dec;

btw thank you very much for your help i havent tried it yet but it looks good so far ill try it when i get home and ill keep you posted

Thanx

### #6 richbria90

Reputation: 1
• Posts: 23
• Joined: 21-January 10

## Re: C++ Decimal to Binary (Recursively)

Posted 31 January 2010 - 04:09 AM

Okay so I am almost done with this.. Just need a little bit more help.. Im having trouble doing the Hex to Dec conversion...

```//Implementation File for Convert Class

#include "Convert.h"
#include <iostream>
#include <cstdlib>
using namespace std;

//Constructors
Convert::Convert()
{
decNum= 0;
binNum= "";
hexNum= "";
}
//Mutator Functions
bool Convert::setDecNum(int dec)
{
decNum = dec;
return true;
}
bool Convert::setBinNum(string bin)
{
binNum = bin;
return true;
}
bool Convert::setHexNum(string hex)
{
hexNum = hex;
return true;
}
// Accessor Functions
int Convert::getDecNum()
{
return decNum;
}
string Convert::getBinNum()
{
return binNum;
}
string Convert::getHexNum()
{
return hexNum;
}
//Utility Functions
void Convert::convDec2Bin(int needsConverted)
{
if(needsConverted!=0)
{
if (needsConverted % 2 == 0)
{
convDec2Bin(needsConverted/2);
binNum = binNum + "0";
return;
}
else
{
convDec2Bin(needsConverted/2);
binNum = binNum + "1";
return;
}
}
else return;
}

//binNum = atoi(needsConverted.c_str());//alpha to integer
//return binNum;
void Convert::hexSwitch(int temp)
{
switch(temp)
{
case 1:
hexNum += "1";
break;
case 2:
hexNum += "2";
break;
case 3:
hexNum += "3";
break;
case 4:
hexNum += "4";
break;
case 5:
hexNum += "5";
break;
case 6:
hexNum += "6";
break;
case 7:
hexNum += "7";
break;
case 8:
hexNum += "8";
break;
case 9:
hexNum += "9";
break;
//if (temp>0 && temp<10)
//itoa(temp,hexNum.push_back(),10)
case 10:
hexNum += "A";
break;
case 11:
hexNum += "B";
break;
case 12:
hexNum += "C";
break;
case 13:
hexNum += "D";
break;
case 14:
hexNum += "E";
break;
case 15:
hexNum += "F";
break;
}

}
void Convert::convDec2Hex(int needsConverted)
{
if(needsConverted>0)
{
if (needsConverted % 16 == 0)
{
convDec2Hex(needsConverted/16);
hexNum = hexNum + "0";
return;
}
else
{
int temp = needsConverted%16;
convDec2Hex(needsConverted/16);
hexSwitch(temp);
}
}
else return;
}
void Convert::convBin2Dec(string needsConverted, int temp)
{
//temp = atoi(needsConverted.c_str());
if (needsConverted!= "")
{

if(needsConverted.at(needsConverted.length()-1) == '0')
{
convBin2Dec(needsConverted.erase(needsConverted.length()-1), temp*2);
return;
}
else
{
convBin2Dec(needsConverted.erase(needsConverted.length()-1), temp*2);
decNum= decNum+temp;
return;
}
}
}
int Convert::hexSwitch2Int(char temp)
{
if (temp >= '1' && temp<= '9')
return (atoi(&temp));
else
{
switch(temp)
{
case 'A':
return (10);
case 'B':
return (11);
case 'C':
return (12);
case 'D':
return (13);
case 'E':
return (14);
case 'F':
return (15);
}
}

}

void Convert::convHex2Dec(string needsConverted, int temp)
{
char lastChar;
int lastCharAsInt;
if (needsConverted!= "")
{
if (needsConverted.length() == 1)
{
char lastChar(needsConverted.at(needsConverted.length()-1));
int lastCharAsInt = hexSwitch2Int(lastChar);
convHex2Dec(needsConverted.erase(needsConverted.length()-1), temp+lastCharAsInt)

}
char lastChar(needsConverted.at(needsConverted.length()-1));
int lastCharAsInt = hexSwitch2Int(lastChar);

convHex2Dec(needsConverted.erase(needsConverted.length()-1), temp*16);
return;
}

return;

}
//if i remove the right char i have to multiply by 16
//*1 *16 *256 *4096
//if i remove the right and it is 1 i add that one to the current total then i multiply by 16

```

I gotta go to bed for work in the morning but any help would be appreciated it is right here at the end that im having problems

### #7 dave007

Reputation: 9
• Posts: 49
• Joined: 24-January 10

## Re: C++ Decimal to Binary (Recursively)

Posted 31 January 2010 - 05:20 AM

Hey, there are few things which you have to take into consideration while writing recursive programming. For example, You are sending 2 parameters to convHex2Dec function. Fist one is the hex string which needs to parse and another is I guess the "Power of 16" by which to multiply. This is right, Howerver you are not storing the multiplication (or cumulative result into any variable). You need to take care of this as well...

Explaination:
For example, if you enter 24E as hex value to be converted. then your code will go through following iterations and will have respectives values in stack

1st Call : convHex2Dec("24E", 1)
lastCharAsInt = E
temp = 1

2nd Call : convHex2Dec("24", 18)
lastCharAsInt = 4
temp = 256 (16 * 16)

3rd Call : convHex2Dec("2", 1)
lastCharAsInt = 2
temp = 4096 (16 * 16 * 16)

After the 1st call, your program should save the vaule of "E * 1" in some variable and give a 2nd call with updated values. Again in 2nd call, your program should save the value of "4 * 16 * 16" in some variable and give a 3rd call and so on, till whole string is consume.

So I have added one extra varible in your code snippet - "decNo" and adding the cumulative result for priting.

Hope above explaination was helpful.. Below is the updated code..

```int Convert::convHex2Dec(string needsConverted, int temp)
{
unsigned long decNo = 0;

if (needsConverted!= "")
{
if (needsConverted.length() == 1)
{
char lastChar(needsConverted.at(needsConverted.length()-1));
int lastCharAsInt = hexSwitch2Int(lastChar);
decNo = lastCharAsInt * temp;
}

char lastChar(needsConverted.at(needsConverted.length()-1));
int lastCharAsInt = hexSwitch2Int(lastChar);
decNo = temp * lastCharAsInt;
decNo += convHex2Dec(needsConverted.erase(needsConverted.length()-1), temp*16);

return decNo;
}

return decNo;
}

```

If you need more help in understanding recursion, then do let us know.

### #8 japanir

• jaVanir

Reputation: 1014
• Posts: 3,025
• Joined: 20-August 09

## Re: C++ Decimal to Binary (Recursively)

Posted 31 January 2010 - 05:45 AM

i know you already have a function to convert from decimal to binary, however i thought to post a simple version, to show a different approach.
here is the recursive code. the function is void though it is easy to alter to strings.

```void decimalToBinary(int decimal)
{
if(decimal > 0)
{
decimalToBinary(decimal / 2);
cout<<(decimal % 2);
}
}

```

### #9 html_dns

Reputation: 0
• Posts: 30
• Joined: 29-December 08

## Re: C++ Decimal to Binary (Recursively)

Posted 31 January 2010 - 06:19 AM

Just an idea, haven't thoroughly read the posts but it looks like you guys are on the ball. You could maybe use the reserved word static to retain the information for each recursion, putting out their. Great work guys

### #10 dave007

Reputation: 9
• Posts: 49
• Joined: 24-January 10

## Re: C++ Decimal to Binary (Recursively)

Posted 31 January 2010 - 06:33 AM

html_dns, on 31 Jan, 2010 - 05:19 AM, said:

Just an idea, haven't thoroughly read the posts but it looks like you guys are on the ball. You could maybe use the reserved word static to retain the information for each recursion, putting out their. Great work guys

Have made few changes in the code. Now you don't even need any ocal variable, not even STATIC,

```int Convert::convHex2Dec(string needsConverted, int temp)
{
//unsigned long decNo = 0;

if (needsConverted!= "")
{
if (needsConverted.length() == 1)
{
char lastChar(needsConverted.at(needsConverted.length()-1));
int lastCharAsInt = hexSwitch2Int(lastChar);
return lastCharAsInt * temp;
}

char lastChar(needsConverted.at(needsConverted.length()-1));
int lastCharAsInt = hexSwitch2Int(lastChar);
//decNo = temp * lastCharAsInt;
return (temp * lastCharAsInt) + convHex2Dec(needsConverted.erase(needsConverted.length()-1), temp*16);

//return decNo;
}

//return decNo;
}

```

Howerver, below statement in the code

```return (temp * lastCharAsInt) + convHex2Dec(needsConverted.erase(needsConverted.length()-1), temp*16);

```

is difficult to understand in first glace and looses the IMPORTANT thing about the programming and that is READABILITY.

So I will still prefer to use the earliar code posted by us.. Thank you for your information about "Static".

### #11 baavgai

• Dreaming Coder

Reputation: 7118
• Posts: 14,835
• Joined: 16-October 07

## Re: C++ Decimal to Binary (Recursively)

Posted 31 January 2010 - 08:29 AM

Just because this bothered me, you really don't need a switch for hexSwitch2Int...
```int hex2Int(char temp) {
if (temp >= '0' && temp<= '9')  { return temp-'0'; }
if (temp >= 'A' && temp<= 'F')  { return (temp-'A') + 10; }
if (temp >= 'a' && temp<= 'f')  { return (temp-'a') + 10; }
return 0;
}

```

For a recursive conversion, the information offered is valid. However, passing a temp variable is a crutch. This will work fine:
```int convHex2Dec(string needsConverted) {
int len = needsConverted.length();
int n = hex2Int(needsConverted.at(len-1));
if (len>1) { n += convHex2Dec(needsConverted.substr(0,len-1)) << 4; };
return n;
}

```

This is actually clearer in a non recursive version:
```int hex2Dec(string needsConverted) {
int n=0, len = needsConverted.length();
for(int i=0; i<len; i++) {
n *= 16;
n += hex2Int(needsConverted.at(i));
}
return n;
}

```

Hope this helps.

### #12 dave007

Reputation: 9
• Posts: 49
• Joined: 24-January 10

## Re: C++ Decimal to Binary (Recursively)

Posted 31 January 2010 - 08:40 AM

baavgai, on 31 Jan, 2010 - 07:29 AM, said:

However, passing a temp variable is a crutch. This will work fine:
```int convHex2Dec(string needsConverted) {
int len = needsConverted.length();
int n = hex2Int(needsConverted.at(len-1));
if (len>1) { n += convHex2Dec(needsConverted.substr(0,len-1)) << 4; };
return n;
}

```

Yes.. I agree with you, however I made minimal changes in his code, so that it will be easy for him to understand it faster.

Thanks for for your effective solution and even code with non-recursion.

### #13 richbria90

Reputation: 1
• Posts: 23
• Joined: 21-January 10

## Re: C++ Decimal to Binary (Recursively)

Posted 31 January 2010 - 08:40 PM

First of all I want to say thank you to everyone all of your information was very helpful. However in my defense... lol.. Alot of the trash I was throwing up there was just to get it working for now... because once I am done there is always room for improvement.

first of all 007 you are right.. if you see in my notes at the bottom I was logically doing the math just having trouble coding it...

second japanir yours is much better and I planned on doing something similar to that...

third html_dns unfortunately you can't use the static modifier because then if you reuse the function on different data you still have that same static value from the initial call

next baavgai thank you.. for the first part I was just trying to be lazy and copy code to fix later... unfortunately I have to use recursion otherwise I would have been done a long time ago... and I agree about the temp variable but I couldnt come up with a better way...