# Recursive function that changes an integer to binary

Printable View

• 04-10-2005
advocation
Recursive function that changes an integer to binary
I need to write a recursive function that takes an integer number (say 12) and change it to binary (1100) and I have no idea how to code it. Does anyone have any ideas?
Also, I have write another recursive function that takes an interger, say 12 again, and will add the two digits so it is 3 (this function isn't as important). Thanks!
Aaron
• 04-10-2005
samGwilliam
The function should take a parameter that tells it what bit it has to evaluate. The function would simply display this particular bit and dcrement that parameter by one before calling itself. The terminating condition would be this parameter equalling 0.

So if you want to display a 32 bit int then the function call would look like:

display (12, 32);

That should get you started.
• 04-10-2005
advocation
Ummm, ok, it sounds great; but I'm lost at how to do it. :)
• 04-10-2005
trippeer
Quote:

Originally Posted by advocation
Ummm, ok, it sounds great; but I'm lost at how to do it. :)

The first thing you need to do is develop an algorithm for converting decimal to binary. You can google that. After you have your algorithm, then you can look at implementation.

edit: http://scholar.hw.ac.uk/site/computi...8.asp?outline= is a good explanation on how to do the conversion, and it leads right to a recursive implementation.
• 04-10-2005
advocation
I got it, cool; thanks!

Oh yeah, any idea on how to do the other problem i have now?
• 04-10-2005
trippeer
Quote:

Originally Posted by advocation
I got it, cool; thanks!

Oh yeah, any idea on how to do the other problem i have now?

For the second part, it seems to me that you want to recursively divide by 10 to break the number down to its digits, then add them up. Your test to break the recursion will be when the remainder is 0.
• 04-10-2005
samGwilliam
Think!

Code:

```void display (int val, int x) {     // Display bit x code goes here.     display (val, x - 1); }```
But make sure you don't infinitely recur. That's all the direction you should need if you have the ability to freely think.