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

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

    Great answers! I guess the answer to my question was "no" I was not missing some obvious solution. Here is the function I will use that condenses the good ideas expressed in the answers.

    • allow caller-supplied mapping of characters (allows base64 encode)
    • checks for negative and zero
    • maps complex numbers into tuples of strings

    
    def int2base(x,b,alphabet='0123456789abcdefghijklmnopqrstuvwxyz'):
        'convert an integer to its string representation in a given base'
        if b<2 or b>len(alphabet):
            if b==64: # assume base64 rather than raise error
                alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
            else:
                raise AssertionError("int2base base out of range")
        if isinstance(x,complex): # return a tuple
            return ( int2base(x.real,b,alphabet) , int2base(x.imag,b,alphabet) )
        if x<=0:
            if x==0:
                return alphabet[0]
            else:
                return  '-' + int2base(-x,b,alphabet)
        # else x is non-negative real
        rets=''
        while x>0:
            x,idx = divmod(x,b)
            rets = alphabet[idx] + rets
        return rets

提交回复
热议问题