# C++, Don't quite get the result I expect...

This topic is 4381 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hello there! Thought this would be the place for my small problem. When I convert from decimal to binary bases with a recursive function, it produces only the two last to digits of the result. If I input 54, it produces 00. If I input 55, it produces 01. Here is the code, would be happy if you could helo me. void toBinary(int dec) { int ans; if(dec <= 1){ cout << dec; return; } ans = dec % 2; toBinary(ans >> 1); cout << ans; }

##### Share on other sites
toBinary(ans >> 1);
Should be:
toBinary(dec >> 1);
I assume it was a typo and you understand the problem, if you don't please ask why you should do that.

##### Share on other sites
Note that x MOD y returns the remainder of the division of x by y, so your code basically just has four outcomes:
0, 1, 00 and 01 [smile]

Ah - beaten to it [smile]
[/edit]

##### Share on other sites
Just a guess but I think it's here:

ans = dec % 2;
toBinary(ans >> 1);
cout << ans;

ans can only be 0 or 1 so when it's passed to toBinary "dec<=1" becomes true and it exits.

I think "toBinary(ans >> 1);" should be "toBinary(dec >> 1);".

Edit: aw crap you guys are too fast

##### Share on other sites
Ahh.. Of course! Thank you guys.. :) Tired eyes always miss stuff like that out.

##### Share on other sites
There's one other thing I am wondering about.. Can I append to an int?

Let me explain what I mean; I have a loop, spitting out numbers like 45, 67, 115, every run. I want a variable that when the loop is over, looks like this: 4567117

Understan me? :)

##### Share on other sites
Quote:
 Original post by BeatOneThere's one other thing I am wondering about.. Can I append to an int?Let me explain what I mean; I have a loop, spitting out numbers like 45, 67, 115, every run. I want a variable that when the loop is over, looks like this: 4567117Understan me? :)

I assume you meant 4567115. If you wanted to store the result as an int you could just for each loop multiply the int with 10[sup]x[/sup]. So if we start with having 45 we assign the "Final" int to 45, we then see 67 is the next number, 67 have two digits so we multiply with 100(two zeros), and then add 67 and then we multiply with 1000 (since 115 have 3 digits) and add 115. So the final calculation would be like this:

Final = (45 * 100 + 67)*1000 + 115

EDIT: A simple (and ugly) code example:
void Add(unsigned int x){	static unsigned int Final = 0;	if( 0 == Final )	{		Final = x;		return;	}	// Calculate number of digits of X by taking the log10, adding one and casting to unsigned int.	unsigned int NumDigits = static_cast<unsigned int>(std::log10(static_cast<float>(x))) + 1;	// Get the multiplier by: 10^NumDigits	unsigned int Multiplier = static_cast<unsigned int>(std::pow(10.0F,static_cast<int>(NumDigits) ) );	Final *= Multiplier;	Final += x;	std::cout << "Final: " << Final << std::endl;}

##### Share on other sites
Thanks for that one! Will check that out later!

##### Share on other sites
Or, you can use the Standard C++ Library to make life a lot easier [wink]

#include <sstream>using std::stringstream;...int var1 = 45;int var2 = 67;int var3 = 115;...// Create the streamstringstream ss;// Output all the variables heress << var1;ss << var2;ss << var3;// ss.str(), which returns a string, is now "4567115", but it's a string and you want an int// Store the intint result = 0;// extract the resultss >> result;// Now, result == 4567115, and you have your combined int, if you just wanted that string, use the ss.str() function.

##### Share on other sites
personally i would just have a string variable which i kept appending the integer to inside the loop. would just be more obvious IMO.

EDIT: bah, drew_benton beat me to it.

##### Share on other sites
I used the method you guys said, I got it to work exept one small detail. It only saves the first number, aka the first loop-round..

stringstream ascii;

while(tWord[x] != '\0')
{
ans = int(tWord[x]);
toBinary(ans);
ascii << ans;
x++;
}
int result = ans;
cout << endl << endl << ans;

The whole application takes a string, converts to its ascii equevilants, converts the ascii number to binary. I want to write out not only the binary, but the ascii numbers..

"The word: BeatOne is
10010-blabla in binary
and 11547-blabla-some-more in asciicode."

##### Share on other sites
Quote:
 Original post by BeatOneWhen I convert from decimal to binary bases [...]void toBinary(int dec)

You don't (and thus the name of your parameter is misleading). All you do is print the binary representation of a number. The number itself is NOT decimal. For example you could write:

toBinary(0x10);
toBinary(020);

And get the result 10000 onscreen. No need to write seperate toBinary methods for decimal, hexadecimal and octal. BTW the internal representation of numbers in a computer is already binary. Funny, huh? :)

##### Share on other sites
There is no such thing as converting an integer variable (int, short, long, etc.) from base X to base Y. It is a variable which represents some value, and does so by having some pattern of bits. If I have fifty-four pennies, then I may write that as 54 pennies in decimal or 0x36 pennies in hex or 066 pennies in octal or 110110 pennies in binary, but I still have the same amount of money.

Instead, there are such things as:

a) outputting a text representation of a number in base Y.
b) inputting a number from what is assumed to be a text representation in base X.

Also, don't use char arrays to represent your text. Use std::string.

##### Share on other sites
For the case of writing out the binary representation of an integer...
std::bitset<sizeof(int) * 8> bs(val);std::cout<<bs;

Boy isn't the standard library nice?

##### Share on other sites
Oh well, as long as the code produces the result I want, I don't really care if the value is converted or just written out. But thanks anyway. :)

##### Share on other sites

This topic is 4381 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Create an account

Register a new account

• ### Forum Statistics

• Total Topics
628714
• Total Posts
2984357

• 23
• 11
• 10
• 13
• 14