General formula for decimal $(x_{10})$ to base $b$ conversion.

binaryfunctions

In general, a decimal number $x_{10}$ can be converded to a base $b$ number throught the following steps;

$\mathbf{Step 1}$ − Divide the decimal number to be converted by the value of the base $b$.

$\mathbf{Step 2}$ − Get the remainder from $\mathbf{Step 1}$ as the rightmost digit (least significant digit) of the base $b$ number.

$\mathbf{Step 3}$ − Divide the quotient of the previous divide by the base $b$.

$\mathbf{Step 4}$ − Record the remainder from $\mathbf{Step 3}$ as the next digit (to the left) of the base $b$ number.

$\mathbf{Step 5}$ – Repeat $\mathbf{Steps 5}$ and $\mathbf{4}$, getting remainders from right to left, until the quotient becomes zero in $\mathbf{Step 3}$.

Can we write down one specific mathematical equation or a function that output a base $b$ number by following these steps when a decimal number $x_{10}$ is inputted?

Best Answer

Conversion of a string of $n$ digits $\underline{d_1 d_2 \ldots d_n}$ in base $b$ to a non-negative integer $x$ is essentially what your matrix does:

$$ x = \sum_{i=1}^n d_i b^{n-i} = d_1 b^{n-1} + d_2 b^{n-2} + \cdots + d_n b^0 $$

Conversion of a positive integer $x$ to a string of digits in base $b$ first finds the string length $n$ by

$$ n = \lfloor \log_b x \rfloor + 1 $$

where $\lfloor \cdot \rfloor$ is the greatest integer function, also called floor function, giving the result of "rounding down". Then the digit $d_i$ is given by

$$ d_i = \lfloor x b^{i-n} \rfloor - b \lfloor x b^{i-n-1} \rfloor $$

This doesn't work for $x=0$, but of course the customary string representing zero in any base is the length-1 string $\underline 0$.

That's the mathematical way, at least. A computer algorithm will more commonly use a recursive approach. In Python, for example (ignoring library functions which will do all this for you):

def itos(x: int, b: int) -> str:
    if x==0:
        return "0"
    digits = ""
    neg = (x<0)
    if neg:
        x = -x
    while x>0:
        '''(x // b) is math.floor(x / b). (x % b) is x - (x // b).'''
        digit = x % b
        if digit<10:
            digit = str(digit)
        else:
            '''The nth letter of the English alphabet'''
            digit = chr(ord('a') + (digit-10))
        digits = digit + digits
        x = x // b
    if neg:
        return "-" + digits
    return digits

Try it online!

This function finds the digits in reverse order, dividing by $b$ as many times as necessary until the result is zero, while using the remainder at each step as the next-to-last digit. This also removes the need to find the length $n$ ahead of time (except maybe in languages like C where one must manually allocate the string memory).