Home >Backend Development >Python Tutorial >How to Convert Integers to Strings in Any Base in Python?

How to Convert Integers to Strings in Any Base in Python?

Barbara Streisand
Barbara StreisandOriginal
2024-12-06 10:28:11405browse

How to Convert Integers to Strings in Any Base in Python?

Converting Integers to Strings in Any Base

Python provides convenient functionality to convert strings to integers using a specified base through the int() function, but converting integers back to strings in different bases poses a challenge. This article aims to address this task and provide a general solution that overcomes limitations found in built-in functions.

The Function int2base()

To address the problem, a function int2base(num, base) is proposed, meeting the following requirements:

  • Converts an integer x to a string str in base b: int(str, b) == x
  • Supports any valid x and b accepted by the int() function

A Surprisingly Simple Solution

Contrary to expectations, a straightforward solution exists:

def numberToBase(n, b):
    if n == 0:
        return [0]
    digits = []
    while n:
        digits.append(int(n % b))
        n //= b
    return digits[::-1]

This solution works for any base from 2 to infinity. If you need to convert a large integer to base 577, for example:

numberToBase(67854 ** 15 - 102, 577)

It correctly returns:

[4, 473, 131, 96, 431, 285, 524, 486, 28, 23, 16, 82, 292, 538, 149, 25, 41, 483, 100, 517, 131, 28, 0, 435, 197, 264, 455]

This result can then be easily converted to any other base as needed.

Understanding the Solution

The key to this solution lies in understanding the representation of numbers in different bases. For instance, in base 10, the number 123 represents (1 10^2) (2 10^1) (3 * 10^0). Similarly, in an arbitrary base b, a number can be represented as a sum of powers of b.

The numberToBase() function works by iteratively dividing the input n by b and collecting the remainders. These remainders, in reverse order, represent the digits of the number in base b.

The above is the detailed content of How to Convert Integers to Strings in Any Base in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn