开发者

How i can convert integer in to 'binary' in python

In Ruby i d开发者_运维百科o so

asd = 123
asd = '%b' % asd # => "1111011"


you can also do string formatting, which doesn't contain '0b':

>>> '{:b}'.format(123)            #{0:b} in python 2.6
'1111011'


in Python >= 2.6 with bin():

asd = bin(123) # => '0b1111011'

To remove the leading 0b you can just take the substring bin(123)[2:].

bin(x)
Convert an integer number to a binary string. The result is a valid Python expression. If x is not a Python int object, it has to define an __index__() method that returns an integer.

New in version 2.6.


bin() works, as Felix mentioned. For completeness, you can go the other way as well.

>>> int('01101100',2)
108
>>> bin(108)
'0b1101100'
>>> bin(108)[2:]
'1101100'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜