Python int to binary string?

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

    As a reference:

    def toBinary(n):
        return ''.join(str(1 & int(n) >> i) for i in range(64)[::-1])
    

    This function can convert a positive integer as large as 18446744073709551615, represented as string '1111111111111111111111111111111111111111111111111111111111111111'.

    It can be modified to serve a much larger integer, though it may not be as handy as "{0:b}".format() or bin().

提交回复
热议问题