Computer Science Canada Decimal to Binary |
Author: | gitoxa [ Tue Dec 09, 2008 6:16 pm ] | ||
Post subject: | Decimal to Binary | ||
I'm fairly new to c++ and I've been having trouble trying to code a recursive decimal to binary converter. I'm trying to pass an integer into the function and return a string in the end. I'm not sure if I'm going about this the right way though. Tips preferred over solutions if possible, as I'm trying to learn. ![]() Here's my code which compiles fine in Dev-CC++ 4.9.9.2, but I get some... weird output.
|
Author: | Saad [ Tue Dec 09, 2008 6:48 pm ] | ||||
Post subject: | Re: Decimal to Binary | ||||
More specifically,
Alternatively, you can look up the functions to convert an integer to a string. |
Author: | gianni [ Tue Dec 09, 2008 6:51 pm ] |
Post subject: | Re: Decimal to Binary |
Tips I think the best way to do this may not be through recursion. You can set this up in a simple for or while loop. Another thing to keep in mind (*wink*) is that each bit in a binary string has a maximum value of 2^(bit position). |
Author: | gitoxa [ Tue Dec 09, 2008 8:51 pm ] |
Post subject: | Re: Decimal to Binary |
gianni @ Tue Dec 09, 2008 6:51 pm wrote: Tips
I think the best way to do this may not be through recursion. You can set this up in a simple for or while loop. Another thing to keep in mind (*wink*) is that each bit in a binary string has a maximum value of 2^(bit position). I already understand recursion enough for the concept of it not to confuse me, I'm trying to just get the coding side of it done in c++ I fiddled around with the idea of it being the ASCII value, but I'm short on time right now so I'll fiddle around with that more later. I found some code for the casting of it, and it works now. |
Author: | md [ Wed Dec 10, 2008 12:04 pm ] |
Post subject: | RE:Decimal to Binary |
You seem to be on the right track - though as has been pointed out you need to properly convert to a character. You should also look at stringstreams and how to convert numbers to strings using them. It should be possible to convert to binary though I do not know the exact code. |
Author: | gitoxa [ Wed Dec 10, 2008 2:06 pm ] |
Post subject: | Re: RE:Decimal to Binary |
md @ Wed Dec 10, 2008 12:04 pm wrote: You should also look at stringstreams and how to convert numbers to strings using them.
This is what I used to convert them. There was also the function itoa() but it was being a pain to implement with my current knowledge |
Author: | OneOffDriveByPoster [ Sun Dec 14, 2008 5:45 pm ] |
Post subject: | Re: Decimal to Binary |
Why not recursion? No function call overhead (and the stack space required). What was the initial converting hint? Add a value to the 0 or 1 to get '0' or '1'. Why not use bitwise-and to test the low bit? Why not use logical right shift to drop that bit? |