Conversion of Integers to Strings in任意进制
Python enables the effortless conversion of strings to integers based on a specified radix using int(str, base). However, the inverse process—generating strings from integers—requires a custom solution.
A function int2base(num, base) is desirable, fulfilling the following criterion:
int(int2base(x, b), b) == x
For any integer x and base b supported by int().
A straightforward implementation of this function consists of:
def numberToBase(n, b): if n == 0: return [0] digits = [] while n: digits.append(int(n % b)) n //= b return digits[::-1]
This approach provides a versatile solution that converts to arbitrary bases. For instance, converting a large number to base 577 would yield the correct result:
numberToBase(67854 ** 15 - 102, 577)
Key Insights:
The above is the detailed content of How to Convert Integers to Strings in Arbitrary Bases in Python?. For more information, please follow other related articles on the PHP Chinese website!