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

前端 未结 27 3143
清歌不尽
清歌不尽 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:52

    A recursive solution for those interested. Of course, this will not work with negative binary values. You would need to implement Two's Complement.

    def generateBase36Alphabet():
        return ''.join([str(i) for i in range(10)]+[chr(i+65) for i in range(26)])
    
    def generateAlphabet(base):
        return generateBase36Alphabet()[:base]
    
    def intToStr(n, base, alphabet):
        def toStr(n, base, alphabet):
            return alphabet[n] if n < base else toStr(n//base,base,alphabet) + alphabet[n%base]
        return ('-' if n < 0 else '') + toStr(abs(n), base, alphabet)
    
    print('{} -> {}'.format(-31, intToStr(-31, 16, generateAlphabet(16)))) # -31 -> -1F
    

提交回复
热议问题