Conversion of Integers to Strings in Arbitrary Bases
This question seeks a method to convert integers into strings in any base. Unlike Python's int(str, base) function, which allows creation of integers from strings of a specified base, the desired approach is its inverse, whereby strings are constructed from integers.
A Simple Solution
Intuitively, people tended to focus on converting to small bases (e.g., less than the English alphabet's length). However, the question demands a universal solution applicable to any base from 2 to infinity.
A straightforward solution is presented below:
def numberToBase(n, b): if n == 0: return [0] digits = [] while n: digits.append(int(n % b)) n //= b return digits[::-1]
This function takes an integer n and a base b as inputs and returns a list of digits representing n in base b. It works by iteratively dividing n by b and collecting the remainders (i.e., digits) in a list. The list is then reversed to obtain the correct order of digits.
For example, to convert 67854**15 - 102 to base 577:
print(numberToBase(67854 ** 15 - 102, 577))
Output:
[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 be further converted into any other desired base.
Key Points
The above is the detailed content of How can integers be converted into strings in arbitrary bases?. For more information, please follow other related articles on the PHP Chinese website!