Python int to binary string?

后端 未结 30 1625
执念已碎
执念已碎 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 05:59

    numpy.binary_repr(num, width=None)

    Examples from the documentation link above:

    >>> np.binary_repr(3)
    '11'
    >>> np.binary_repr(-3)
    '-11'
    >>> np.binary_repr(3, width=4)
    '0011'
    

    The two’s complement is returned when the input number is negative and width is specified:

    >>> np.binary_repr(-3, width=3)
    '101'
    >>> np.binary_repr(-3, width=5)
    '11101'
    

提交回复
热议问题