Here's what I have come up with for the code on converting a decimal number to binary using a string:
Code:
// This program will test the function BtoD
// int BtoD (string Binary); is the prototype
// will convert any byte (8bits) from binary to decimal
#include <iostream>
#include <string>
using namespace std;
string dec2bin(int Decimal);
string dec2bin(int Decimal)
{
int steps[] = {128, 64, 32, 16, 8, 4, 2, 1};
string binary;
if(Decimal > 0)
{
int stepLen = sizeof(steps) / sizeof(int);
for(int x = 0; x < stepLen; x++)
{
if(Decimal >= steps[x])
{
Decimal -= steps[x];
binary += "1";
}
else
binary += "0";
}
}
else
binary = "0";
return binary;
}
// The driver program follows
int main()
{
cout << "Enter an integer no larger than 255: ";
int Decimal;
cin >> Decimal;
if (Decimal > 255)
{
cout << "Please follow instructions" << endl;
}
else
{
cout << "Binary: " << dec2bin(Decimal) << endl;
}
system("PAUSE");
return 0;
}
After this, how would I go about making the program capable of distinguishing between a binary or decimal input and then converting it?