Python int to binary string?

后端 未结 30 2273
执念已碎
执念已碎 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:55

    For those of us who need to convert signed integers (range -2**(digits-1) to 2**(digits-1)-1) to 2's complement binary strings, this works:

    def int2bin(integer, digits):
        if integer >= 0:
            return bin(integer)[2:].zfill(digits)
        else:
            return bin(2**digits + integer)[2:]
    

    This produces:

    >>> int2bin(10, 8)
    '00001010'
    >>> int2bin(-10, 8)
    '11110110'
    >>> int2bin(-128, 8)
    '10000000'
    >>> int2bin(127, 8)
    '01111111'
    

提交回复
热议问题