How to convert an integer to a string in any base?

前端 未结 27 3087
清歌不尽
清歌不尽 2020-11-22 02:25

Python allows easy creation of an integer from a string of a given base via

int(str, base). 

I want to perform the inverse: creati

27条回答
  •  北海茫月
    2020-11-22 02:48

    Surprisingly, people were giving only solutions that convert to small bases (smaller then the length of the English alphabet). There was no attempt to give a solution which converts to any arbitrary base from 2 to infinity.

    So here is a super simple solution:

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

    so if you need to convert some super huge number to the base 577,

    numberToBase(67854 ** 15 - 102, 577), will give you a correct solution: [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],

    Which you can later convert to any base you want

提交回复
热议问题