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

前端 未结 27 3097
清歌不尽
清歌不尽 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:58
    def baseN(num,b,numerals="0123456789abcdefghijklmnopqrstuvwxyz"):
        return ((num == 0) and numerals[0]) or (baseN(num // b, b, numerals).lstrip(numerals[0]) + numerals[num % b])
    

    ref: http://code.activestate.com/recipes/65212/

    Please be aware that this may lead to

    RuntimeError: maximum recursion depth exceeded in cmp
    

    for very big integers.

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

    http://code.activestate.com/recipes/65212/

    def base10toN(num,n):
        """Change a  to a base-n number.
        Up to base-36 is supported without special notation."""
        num_rep={10:'a',
             11:'b',
             12:'c',
             13:'d',
             14:'e',
             15:'f',
             16:'g',
             17:'h',
             18:'i',
             19:'j',
             20:'k',
             21:'l',
             22:'m',
             23:'n',
             24:'o',
             25:'p',
             26:'q',
             27:'r',
             28:'s',
             29:'t',
             30:'u',
             31:'v',
             32:'w',
             33:'x',
             34:'y',
             35:'z'}
        new_num_string=''
        current=num
        while current!=0:
            remainder=current%n
            if 36>remainder>9:
                remainder_string=num_rep[remainder]
            elif remainder>=36:
                remainder_string='('+str(remainder)+')'
            else:
                remainder_string=str(remainder)
            new_num_string=remainder_string+new_num_string
            current=current/n
        return new_num_string
    

    Here's another one from the same link

    def baseconvert(n, base):
        """convert positive decimal integer n to equivalent in another base (2-36)"""
    
        digits = "0123456789abcdefghijklmnopqrstuvwxyz"
    
        try:
            n = int(n)
            base = int(base)
        except:
            return ""
    
        if n < 0 or base < 2 or base > 36:
            return ""
    
        s = ""
        while 1:
            r = n % base
            s = digits[r] + s
            n = n / base
            if n == 0:
                break
    
        return s
    
    0 讨论(0)
  • 2020-11-22 02:58

    Well I personally use this function, written by me

    import string
    
    def to_base(value, base, digits=string.digits+string.ascii_letters):    # converts decimal to base n
    
        digits_slice = digits[0:base]
    
        temporary_var = value
        data = [temporary_var]
    
        while True:
            temporary_var = temporary_var // base
            data.append(temporary_var)
            if temporary_var < base:
                break
    
        result = ''
        for each_data in data:
            result += digits_slice[each_data % base]
        result = result[::-1]
    
        return result
    

    This is how you can use it

    print(to_base(7, base=2))

    Output: "111"

    print(to_base(23, base=3))

    Output: "212"

    Please feel free to suggest improvements in my code.

    0 讨论(0)
提交回复
热议问题