Python int to binary string?

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

    Yet another solution with another algorithm, by using bitwise operators.

    def int2bin(val):
        res=''
        while val>0:
            res += str(val&1)
            val=val>>1     # val=val/2 
        return res[::-1]   # reverse the string
    

    A faster version without reversing the string.

    def int2bin(val):
       res=''
       while val>0:
           res = chr((val&1) + 0x30) + res
           val=val>>1    
       return res 
    

提交回复
热议问题