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

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

    I know this is an old post, but I'm just leaving my solution here just in case.

    def decimal_to_given_base(integer_to_convert, base):
         remainder = integer_to_convert // base
         digit = integer_to_convert % base
         if integer_to_convert == 0:
             return '0'
         elif remainder == 0:
             return str(digit)
         else:
             return decimal_to_given_base(remainder, base) + str(digit)
    
    0 讨论(0)
  • 2020-11-22 02:35

    This is an old question but I thought i'd share my take on it as I feel it is somewhat simpler that other answers (good for bases from 2 to 36):

    def intStr(n,base=10):
        if n < 0   : return "-" + intStr(-n,base)         # handle negatives
        if n < base: return chr([48,55][n>9] + n)         # 48 => "0"..., 65 => "A"...
        return intStr(n//base,base) + intStr(n%base,base) # recurse for multiple digits
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-11-22 02:40
    def base(decimal ,base) :
        list = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        other_base = ""
        while decimal != 0 :
            other_base = list[decimal % base] + other_base
            decimal    = decimal / base
        if other_base == "":
            other_base = "0"
        return other_base
    
    print base(31 ,16)
    

    output:

    "1F"

    0 讨论(0)
  • 2020-11-22 02:40

    Another short one (and easier to understand imo):

    def int_to_str(n, b, symbols='0123456789abcdefghijklmnopqrstuvwxyz'):
        return (int_to_str(n/b, b, symbols) if n >= b else "") + symbols[n%b]
    

    And with proper exception handling:

    def int_to_str(n, b, symbols='0123456789abcdefghijklmnopqrstuvwxyz'):
        try:
            return (int_to_str(n/b, b) if n >= b else "") + symbols[n%b]
        except IndexError:
            raise ValueError(
                "The symbols provided are not enough to represent this number in "
                "this base")
    
    0 讨论(0)
  • 2020-11-22 02:42
    "{0:b}".format(100) # bin: 1100100
    "{0:x}".format(100) # hex: 64
    "{0:o}".format(100) # oct: 144
    
    0 讨论(0)
提交回复
热议问题