by MXP » Fri May 13, 2005 12:32 am
A number can be represented as the sum of powers of some base. For example 1604 can be written as 1 * 10^3 + 6 * 10^2 + 0 * 10^1 + 4 * 10^0. A binary number 1101 can be represented in a similar way: 1 * 2^3 + 1 * 2^2 + 0 * 2^1 + 1 * 2^0. Integer division in C++ can help you find the multiple on each power. For example 1604 / 10^3 = 1, 604 / 10^2 = 6, 4 / 10^1 = 0, 4 / 10^0 = 4 and a similar method works with base 2.
This implies a method of converting between bases. Given a number X, you can convert it to any base N by first finding the largest power of N, we'll say this is p, such that X / N^p != 0. You can find p using logarithms. p = ln X / ln N. Your algorithm will continue like this:
while p >= 0
1. output X / N^p
2. X = X - N^p
3. p = p - 1
To convert to base 2, just set N = 2
Need information on a function I've posted? Chances are it's at the
MSDN.