简体   繁体   English

我如何在python中将整数转换为'二进制'

[英]How i can convert integer in to 'binary' in python

In Ruby i do so 在Ruby中,我这样做

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

in Python >= 2.6 with bin() : 在Python> = 2.6 with bin()

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

To remove the leading 0b you can just take the substring bin(123)[2:] . 要删除前导0b您可以只取子串bin(123)[2:]

bin(x) 滨(X)
Convert an integer number to a binary string. 将整数转换为二进制字符串。 The result is a valid Python expression. 结果是一个有效的Python表达式。 If x is not a Python int object, it has to define an __index__() method that returns an integer. 如果x不是Python int对象,则必须定义一个返回整数的__index__()方法。

New in version 2.6. 2.6版中的新功能。

you can also do string formatting, which doesn't contain '0b' : 你也可以做字符串格式,不包含'0b'

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

bin() works, as Felix mentioned. 正如费利克斯所说,bin()有效。 For completeness, you can go the other way as well. 为了完整起见,您也可以采用其他方式。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM