Solved

# Convert Decimal to Binary Using *Recursion*

Posted on 2007-11-21

Im trying to write code that will take a decimal and convert it to it's 2's complement. Ive been trying to figure it out but i can only get it to working using the functions as void, not string as the requirements have been specified. The only way that has worked so far is through iteration and that is not allowed.

The functions rquired are basically what is being the part that wont allow me to continue.

Function main() calls function string convert(int decimal, int n) that receives the number and returns a string that represents the corresponding binary number in n bits format, where n is the minimum number of bits used to display the binary number.

Function convert() will have to call the *recursive* function string dectobin(int decimal) that receives the decimal number and returns a string that represents the corresponding binary number in free format (that is, with just as many bits as needed to represent the value). Thus, it is the task of convert() to add the (0's and 1's) to the string returned by dectobin() so that the binary number is in n bits format.

The first int in the txt file will be taken in through string convert() as the number of bits, then using that to set the displayed number of bits from the 2's complement representation from function string dectobin().

Example of input:

8

123

-45

72

0

-1534

2341

-8

Example of output:

Decimal:2's complement (8 bits minimum)

---------------------------------------

123 : 01111011

-45 : 11010011

72 : 01001000

0 : 00000000

-1534 : 101000000010

2341 : 100100100101

-8 : 11111000

(i had a previous post about a different part of this that i was working on until i found out it wasnt recursive at all and that i basically had to start from sqaure 1.)