# Converting Decimal to Binary

My program transforms decimal numbers to binary representation.  But I need it to transform it to 16 bit binary representation, mine only transforms to regular binary.
For example,  Mine: 25 = 11001 but it should be 0000000000011001.  This is my program:
#include <iostream>

using namespace std;

void dectobin(int num, int base);

int main()
{
int decimalnum;
int base;

base = 2;

cout<<"Enter the number in decimal: ";
cin>>decimalnum;
cout<<endl;
cout<<"Decimal: "<<decimalnum<<" = ";
dectobin(decimalnum, base);
cout<< " Binary" <<endl;

return 0;

}
void dectobin(int num, int base)
{
if(num > 0)
{
dectobin(num/base, base);
cout<<num % base;
}
}
What do I have to do to make it print out the remaining digits?  Please Advise
###### Who is Participating?

Commented:
Try this:

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

int main()
{
int decimalnum;
int base;

base = 2;

cout<<"Enter the number in decimal: ";
cin>>decimalnum;
cout<<endl;
cout<<"Decimal: "<<decimalnum<<" = ";
dectobin(decimalnum, base);
cout<< " Binary" <<endl;
cin >> base;
return 0;

}
void dectobin(int num, int base, int count)
{
if(num > 0 || count < 16)
{
dectobin(num/base, base, ++count);
cout<<num % base;
char c2[] = "0";
}
}

Regards, Alex
0

Commented:
You could easily do that by switching from a recursive function to a 'linear one, e.g.

void
dectobin (unsigned int b) {

if ( b & mask) {

cout << 1;

} else {

cout << 0;
}
}
}
0

Commented:
You may remove these lines as i needed them on my IDE only:

>>     cin >> base;

>>           char c2[] = "0";

Regards, Alex

0

Commented:
std::bitset<> is nice for this:
--------8<--------
#include <iostream>
#include <bitset>

int main(int argc,const char *argv[])
{
std::cout << std::bitset<16>(atoi(*++argv)) << '\n';
}
--------8<--------
0

Commented:
Hi steve3164!
It is far better to use a direct method to do this rather simple function instead of a recursive one; because as you may know recursive functions are very inefficient due to their excessive use of stack memory as well as their low speed.
This piece of code can do what you need. I have used unsigned short int instead of unsigned int because you are using 16 bit data:

#include <iostream.h>

void dectobin(unsigned short int num);

void main(void)
{
unsigned short int number;
cout<<"Enter a decimal integer: ";
cin>>number;
cout<<"\nBinary representation: ";
dectobin(number);
cout<<endl;
}

void dectobin(unsigned short int num)
{
unsigned int powerOf2=0x8000;
while (powerOf2!=0)
{
if (num>=powerOf2)
{
num^=powerOf2;  //Equivalent to num-= powerOf2;
cout<<1;
}
else
cout<<0;
powerOf2=powerOf2>>1;
}
}
0

Author Commented:
thanks itsmeandnobodyelse!!!

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.