Recursive function that changes an integer to binary

• 04-10-2005
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
Ummm, ok, it sounds great; but I'm lost at how to do it. :)
• 04-10-2005
trippeer
Quote:

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
I got it, cool; thanks!

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

```void display (int val, int x) {     // Display bit x code goes here.     display (val, x - 1); }```