Python int to binary string?

后端 未结 30 1628
执念已碎
执念已碎 2020-11-22 05:34

Are there any canned Python methods to convert an Integer (or Long) into a binary string in Python?

There are a myriad of dec2bin() functions out on Google... But I

30条回答
  •  既然无缘
    2020-11-22 06:00

    If you want a textual representation without the 0b-prefix, you could use this:

    get_bin = lambda x: format(x, 'b')
    
    print(get_bin(3))
    >>> '11'
    
    print(get_bin(-3))
    >>> '-11'
    

    When you want a n-bit representation:

    get_bin = lambda x, n: format(x, 'b').zfill(n)
    >>> get_bin(12, 32)
    '00000000000000000000000000001100'
    >>> get_bin(-12, 32)
    '-00000000000000000000000000001100'
    

    Alternatively, if you prefer having a function:

    def get_bin(x, n=0):
        """
        Get the binary representation of x.
    
        Parameters
        ----------
        x : int
        n : int
            Minimum number of digits. If x needs less digits in binary, the rest
            is filled with zeros.
    
        Returns
        -------
        str
        """
        return format(x, 'b').zfill(n)
    

提交回复
热议问题