Is there any kind of method to move between bases?
I know that there are methods to convert between base x to base y, but I'm looking for something general which won't limit me. Is it possible? Maybe there is some kind of equation.
Is there any kind of method to move between bases?
I know that there are methods to convert between base x to base y, but I'm looking for something general which won't limit me. Is it possible? Maybe there is some kind of equation.
There are at least two different algorithms you might want to use for converting a number $n$ from base $x$ to base $y$, depending on whether you'd rather do your arithmetic in base $x$ or base $y$.
If you're more comfortable doing arithmetic in your starting base:
Write $n=ay+b$ where $0 \leq b < y$ (that is, do "division with remainder" on $n$). Then $b$ will be the rightmost digit of your new representation of $n$, and you repeat the process on $a$ to get all the other digits. Stop when $a$ is less than $y$ (at which point $a$ will be the leftmost digit of your number).
For example, say we want to write the base-ten number $23504$ in base $7$. Then:
Putting all this together, we have $23504_{\mathrm{ten}}=125345_7$.
If you're more comfortable doing arithmetic in your ending base:
Start at the left end of your number and keep a running total. As long as you still have more digits, multiply your running total by $x$ and add the next digit to it. When you run out of digits, your running total is the converted number.
For example, say we want to write the base-$7$ number $125345_7$ in base ten. Then:
So again this demonstrates that $125345_7=23504_{\mathrm{ten}}$ (but starting from the other end).
Finally, maybe you're not comfortable doing arithmetic in either base. If there's some base $z$ you are comfortable doing arithmetic in, that's OK! Just use the second algorithm to convert from base $x$ to base $z$, and the first one to convert from base $z$ to base $y$.
To change bases you use the division algorithm: for an integer $n$ (in any base) and new base $y$, there exists a quotient $q$ and remainder $r$ such that $$n = qy + r, \qquad 0\leq r < y.$$ You can compute $q$ and $r$ by performing long division of $n$ by $y$ in base $x$.
The remainder $r$ then becomes the least significant digit (ones digit) of the number $n$ in base $y$. Repeat the process, using $q$ for $n$, to find the next digits.
(number).toString(base)for bases up to $36$, or you can adapt this JavaScript code to work with bases above $36$. – Feb 25 '13 at 20:02