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

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

    I made my function to do this. Run well on windows 10, python 3.7.3.

    def number_to_base(number, base, precision = 10):
        if number == 0:
            return [0]
        
        positive = number >= 0
        number = abs(number)
        
        ints = []  # store the integer bases
        floats = []  # store the floating bases
    
        float_point = number % 1
        number = int(number)
        while number:
            ints.append(int(number%base))
            number //= base
        ints.reverse()
        
        while float_point and precision:
            precision -= 1
            float_point *= base
            floats.append(int(float_point))
            float_point = float_point - int(float_point)
    
        return ints, floats, positive
    
    
    def base_to_str(bases, string="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"):
        """bases is a two dimension list, where bases[0] contains a list of the integers,
        and bases[1] contains a list of the floating numbers, bases[2] is a boolean, that's
        true when it's a positive number
        """
        ints = []
        floats = []
    
        for i in bases[0]:
            ints.append(string[i])
    
        for i in bases[1]:
            floats.append(string[i])
    
        if len(bases[1]) > 0:
            return (["-", ""][bases[2]] + "".join(ints)) + "." + ("".join(floats))
        else:
            return (["-", ""][bases[2]] + "".join(ints))
        
    
        
    

    Example:

    >>> base_to_str(number_to_base(-6.252, 2))
    '-110.0100000010'
    

提交回复
热议问题