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;
}