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

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

    Recursive

    I would simplify the most voted answer to:

    BS="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    def to_base(n, b): 
        return "0" if not n else to_base(n//b, b).lstrip("0") + BS[n%b]
    

    With the same advice for RuntimeError: maximum recursion depth exceeded in cmp on very large integers and negative numbers. (You could usesys.setrecursionlimit(new_limit))

    Iterative

    To avoid recursion problems:

    BS="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    def to_base(s, b):
        res = ""
        while s:
            res+=BS[s%b]
            s//= b
        return res[::-1] or "0"
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-11-22 02:52
    def base_conversion(num, base):
        digits = []
        while num > 0:
            num, remainder = divmod(num, base)
            digits.append(remainder)
        return digits[::-1]
    
    0 讨论(0)
  • 2020-11-22 02:54
    >>> import string
    >>> def int2base(integer, base):
            if not integer: return '0'
            sign = 1 if integer > 0 else -1
            alphanum = string.digits + string.ascii_lowercase
            nums = alphanum[:base]
            res = ''
            integer *= sign
            while integer:
                    integer, mod = divmod(integer, base)
                    res += nums[mod]
            return ('' if sign == 1 else '-') + res[::-1]
    
    
    >>> int2base(-15645, 23)
    '-16d5'
    >>> int2base(213, 21)
    'a3'
    
    0 讨论(0)
  • 2020-11-22 02:54
    def dec_to_radix(input, to_radix=2, power=None):
        if not isinstance(input, int):
            raise TypeError('Not an integer!')
        elif power is None:
            power = 1
    
        if input == 0:
            return 0
        else:
            remainder = input % to_radix**power
            digit = str(int(remainder/to_radix**(power-1)))
            return int(str(dec_to_radix(input-remainder, to_radix, power+1)) + digit)
    
    def radix_to_dec(input, from_radix):
        if not isinstance(input, int):
            raise TypeError('Not an integer!')
        return sum(int(digit)*(from_radix**power) for power, digit in enumerate(str(input)[::-1]))
    
    def radix_to_radix(input, from_radix=10, to_radix=2, power=None):
        dec = radix_to_dec(input, from_radix)
        return dec_to_radix(dec, to_radix, power)
    
    0 讨论(0)
  • 2020-11-22 02:55

    Here is a recursive version that handles signed integers and custom digits.

    import string
    
    def base_convert(x, base, digits=None):
        """Convert integer `x` from base 10 to base `base` using `digits` characters as digits.
        If `digits` is omitted, it will use decimal digits + lowercase letters + uppercase letters.
        """
        digits = digits or (string.digits + string.ascii_letters)
        assert 2 <= base <= len(digits), "Unsupported base: {}".format(base)
        if x == 0:
            return digits[0]
        sign = '-' if x < 0 else ''
        x = abs(x)
        first_digits = base_convert(x // base, base, digits).lstrip(digits[0])
        return sign + first_digits + digits[x % base]
    
    0 讨论(0)
提交回复
热议问题