How can I improve this C++ program?

I made a simple decimal to binary converter, but it's only my second program, so I don't know much.
Instead of printing every digit separately, is it possible to add each decimal to a variable as it gets them and then just print that variable at the end? If that makes sense? Also is there a better way than having all these if statements? And is there a way to stop the user entering any more than 2 digits? Sorry if I'm not making any sense. :D

#include <iostream>
using namespace std;

int GetNumber()
{
int x;
cin >> x;
return x;
}

void Convert()
{
int x = GetNumber();
if
(x >= 128)
{
cout << 1;
x = x - 128;
}
else
cout << 0;
if
(x >= 64)
{
cout << 1;
x = x - 64;
}
else
cout << 0;
if
(x >= 32)
{
cout << 1;
x = x - 32;
}
else
cout << 0;
if
(x >= 16)
{
cout << 1;
x = x - 16;
}
else
cout << 0;
if
(x >= 8)
{
cout << 1;
x = x - 8;
}
else
cout << 0;
if
(x >= 4)
{
cout << 1;
x = x - 4;
}
else
cout << 0;
if
(x >= 2)
{
cout << 1;
x = x - 2;
}
else
cout << 0;
if
(x >= 1)
{
cout << 1 << endl;
x = x - 1;
}
else
cout << 0 << endl;
}

int main()
{
cout << "INTEGER TO BINARY CONVERTER:" << endl;
cout << "Enter a 1 or 2 digit integer..." << endl;
Convert();
system("pause");
return 0;
}

Well, you probably know that this is already done by the stream, so as far as optimizing.... well, it has been done already. That's what I can say.

But in the spirit of keeping this academic, you can improve this by using a series of integer divisions, plus the algorithm is the same for any base, not just binary.

Take number to hexadecimal as an example: logarithm(base16, X) where X is the number to convert will let you know how many digits the number is when converted to base 16 because it is the integer part of the logarithm + 1. Example: log(16, 16) = 1. This means that the converted number will contain 2 digits. In fact, the conversion should yield 0x10. You can therefore use a loop from log(base, X) to 0 (reducing by one on every iteration) and calculate the different digits by means of integer division.

Last edited on
Topic archived. No new replies allowed.