5 Best Ways to Convert Integer to Base N in Python

πŸ’‘ Problem Formulation:

Converting an integer to a different base is a common task in programming, particularly in areas involving cryptography, data encoding, and computer architecture. This article describes five methods to convert an integer from base 10 to any other base ‘n’. For example, given the integer 42, and the desired base 5, the output should be the string ‘132’, representing the base-5 equivalent of the decimal number 42.

Method 1: Using Recursion

The recursive method involves creating a function that calls itself with a reduced problem size until it reaches a base case. It constructs the base-n representation of an integer by recursively dividing the number by the base and building the result string from the remainders.

Here’s an example:

def convert_to_base_n_recursive(number, base):
    if number < base:
        return str(number)
    else:
        return convert_to_base_n_recursive(number // base, base) + str(number % base)

print(convert_to_base_n_recursive(42, 5))

Output: ‘132’

The snippet defines a function convert_to_base_n_recursive() that uses recursion to build the base-n representation. It uses floor division and modulus to reduce the number and accumulate the result string, respectively.

Method 2: Using Iteration

This method employs a while loop to repeatedly divide the integer by the base while collecting the remainders to construct the base-n number in the reverse order. This is more efficient than using recursion, as it does not require the overhead of multiple function calls.

Here’s an example:

def convert_to_base_n_iterative(number, base):
    result = ''
    while number > 0:
        result = str(number % base) + result
        number //= base
    return result or '0'

print(convert_to_base_n_iterative(42, 5))

Output: ‘132’

The code snippet provides a definition of the function convert_to_base_n_iterative() which utilizes a while loop to perform the conversion. The or ‘0’ ensures that 0 is returned when the number is 0 rather than an empty string.

Method 3: Using the Format Function

The built-in format() function in Python can be used to convert numbers to various bases, including binary, octal, and hexadecimal, but with a slight modification, it can also support other bases by using a custom format specification.

Here’s an example:

def convert_to_base_n_format(number, base):
    if number < base:
        return str(number)
    return format(number, 'x').replace('a', '10').replace('b', '11').replace('c', '12').replace('d', '13').replace('e', '14').replace('f', '15')

print(convert_to_base_n_format(42, 16))

Output: ‘2a’

In this example, the convert_to_base_n_format() function uses str.format() with a specifier for hexadecimal conversion (x) and subsequently replaces hex characters with their decimal equivalents to simulate other bases.

Method 4: Using the Divmod Function

The divmod() function provides a convenient way to get both the quotient and the remainder in one call, simplifying the iterative process of converting an integer to base n by eliminating separate division and modulus operations.

Here’s an example:

def convert_to_base_n_divmod(number, base):
    digits = "0123456789abcdefghijklmnopqrstuvwxyz"
    if number == 0:
        return "0"
    result = ""
    while number:
        number, remainder = divmod(number, base)
        result = digits[remainder] + result
    return result

print(convert_to_base_n_divmod(42, 5))

Output: ‘132’

The function convert_to_base_n_divmod() constructs the base-n number using divmod() to get the division’s quotient and remainder. It uses the digits string to map the remainder to a character, building the number from least significant digit to most.

Bonus One-Liner Method 5: Using Base Conversion Packages

Third-party Python packages like ‘numpy’ or ‘bitstring’ provide utility functions for base conversion. Leveraging these can offer a concise and often optimized approach to converting integers to a different base. Below is an example using numpy:

Here’s an example:

import numpy as np

def convert_to_base_n_package(number, base):
    return np.base_repr(number, base)

print(convert_to_base_n_package(42, 5))

Output: ‘132’

The convert_to_base_n_package() function uses numpy’s method base_repr() to perform the base conversion. This one-liner is highly readable and avoids writing custom conversion logic altogether.

Summary/Discussion

  • Method 1: Recursive Approach. Intuitive and easy to understand. It may lead to a stack overflow for large numbers.
  • Method 2: Iterative Approach. Efficient and avoids the recursion overhead. It pleasantly handles 0 as input without additional checks.
  • Method 3: Using Format Function. Relies on built-in functions, but non-standard bases require additional string replacement which might not scale for larger bases.
  • Method 4: Using Divmod Function. Simplifies the iterative logic into fewer lines of code and is easy to read. It also naturally extends to alphanumeric bases beyond 10.
  • Method 5: Using Base Conversion Packages. Requires an external package but offers simplicity and can be far more optimized than native Python functions.