Solved

# Recursion: Decimal to Binary

Posted on 2004-08-11

My program reads decimal numbers from an input file and outputs them in binary form. If the numbers are negative it outputs them in 2's complement form. The thing that is wrong with my program is that I need function main() to call function "string convert(int decimal)" and receive the decimal number and returns a string that represents the corresponding binary number in 16 bits format. Also, I think I already have this but function "convert()" will have to call the recursive function "string dectobin(int decimal)" and receive the decimal number and returns a string that represents the corresponding binary number in free format. Thus, it is the task of "convert()" to add the 0's (or 1's) to string returned by "dectobin()" so that the binary number is in 16 bits format. I think the "void" part in my program is recursive and does the function "convert()". Can anybody help me. Here is my program and contents of input file:

Input3:

-8

123

45

72

-1534

-2341

#include <iostream>

#include <fstream>

using namespace std;

void dectobin(int inp, int base, int count = 0);

int main()

{

ifstream inFile; //input file stream

ofstream outFile; //output file stream

inFile.open("input3.txt"); //open input file

outFile.open("output.txt"); //open output file

int decimalnum[6]; //declare array has 6 integers

int base;

int i;

base = 2;

cout<<"Enter the number in decimal: "<<endl;

if(!outFile) //check for errors in output file

{

cout<<"Cannot open output file!"<<endl;

}

if(!inFile)

{

cout<<"Cannot open input file!"<<endl; //check for errors for input file

return 1;

}

else // no errors do this

for (i=0 ;i<6;i++) { //loop retrieves the integers

inFile>>decimalnum[i]; //implement the integers from input file

cout<<"Decimal: "<<decimalnum[i]<<" = "; //output the integers

dectobin(decimalnum[i], base); //transfer from dec to bin

cout<< " in Binary" <<endl;

}

return 0;

}

void dectobin(int inp, int base, int count)

{

//first cast to 16 bits signed, then to 16 bits unsigned

unsigned short num = (unsigned short)(short)inp;

if(inp > 0 || count < 16)

{

dectobin(num/base, base, ++count);

cout<<num % base;

}

}