2
$\begingroup$

I have multiple numbers (e.g. [1, 4, 2]) where each number can be one of a specified range of numbers (e.g. [0-1, 0-5, 0-3]). I think one can represent my so chosen numbers by seeing them as digits of a number in the mixed radix numeral system with different bases for each position. In the above example, the bases would be [2, 6, 4] and the number would be 1 4 2.

With the bases given in this example one could specify 48 different numbers (2 * 6 * 4). If I know the bases, how can I construct an algorithm that converts such a number to another number in a standard positional numeral system (like e.g. decimal, binary or hexadecimal) without just building a big generated lookup table? The conversion has to be bijective and there should not be any gaps - so for this example the mixed radix numbers should be represented by the integers from 0 to (inclusive) 47 in the decimal system.

Actually I want to encode these mixed radix numbers in binary data, so a gapless and bijective conversion to the binary system would be sufficient.

$\endgroup$
1
  • $\begingroup$ Generalize the usual base conversion algorithm. $\endgroup$ Commented May 6, 2016 at 15:55

1 Answer 1

3
$\begingroup$

If you have numbers $x_1,\ldots,x_n$ in the ranges $x_1 \in \{0,\ldots,b_1-1\},\ldots,x_n \in \{0,\ldots,b_n-1\}$, you can get a number in the range $\{0,\ldots,b_1\ldots b_n-1\}$ using the formula $$ x_n + b_n x_{n-1} + b_n b_{n-1} x_{n-2} + \cdots + b_n b_{n-1} \cdots b_2 x_1 = \\ x_n + b_n (x_{n-1} + b_{n-1} (x_{n-2} + \cdots )). $$ The second formula gives an efficient way of calculating the transformation (from inside out), and also hints at calculating the inverse transformation efficiently.

$\endgroup$
1
  • $\begingroup$ I already thought that the solution should not be very difficult, but this makes it very clear - thank you! $\endgroup$
    – mxscho
    Commented May 6, 2016 at 16:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.