2

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.

mxscho
  • 133
  • 7

1 Answers1

3

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.

Yuval Filmus
  • 280,205
  • 27
  • 317
  • 514