Help comes to those who first help themselves. In other words, what have you done so far?
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
Post your code then. Converting from any base to decimal is a good start.
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
It depends on how you plan to represent the result. This is especially important when converting from base 10 to base 2, because if you're planning on storing the result in an integer type, you can't cover the full range. For example, the largest 32-bit value is ten digits, but the binary representation of that value is 32 digits.
Ideally you would store the represented value as a string and then convert as necessary for calculations. In that case, it's a simple matter of prepending a string with each digit (or appending and reversing at the end):
void dtob(int value, std::string& result)
{
result.clear();
while (value != 0) {
result.insert(result.begin(), (value % 2) + '0');
value /= 2;
}
}
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401