Computing Library › Number Systems & Information
Number Systems & Information

Base Conversion

Converting a number between bases uses repeated division for the integer part and repeated multiplication for the fraction.

Integer part: divide and record remainders

To convert a decimal integer to base b, repeatedly divide by b and record each remainder. The remainders, read from last to first, are the digits. Converting 47 to base 16 gives remainders 15 then 2, so 0x2F.

From base b to decimal

Kronos motion — conversion efficiency

Apply positional notation: multiply each digit by its power of the base and sum. This direction is a single pass and needs no division.

Fractional part: multiply and record integer parts

For the fraction, repeatedly multiply by b and record the integer part that appears each time. Converting 0.625 to binary gives 0.101, since 0.625×2=1.25, 0.25×2=0.5, 0.5×2=1.0.

Shortcut through binary

Between binary, octal, and hexadecimal, skip decimal entirely: group bits in threes for octal or fours for hexadecimal. This is exact and fast because the bases are all powers of two.

Non-terminating fractions

A fraction that terminates in one base may repeat forever in another. One tenth is exact in decimal but a repeating binary fraction, which is a root cause of floating-point rounding error.

python
def to_base(n, b):
    if n == 0:
        return '0'
    digs = '0123456789ABCDEF'
    out = ''
    while n:
        out = digs[n % b] + out
        n //= b
    return out
print(to_base(47, 16))  # '2F'