How can I convert an integer to 'binary' in python

In Ruby, I do it

asd = 123
asd = '%b' % asd # => "1111011"
+3
source share
3 answers

you can also format strings that don't contain '0b':

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

in Python> = 2.6 s bin():

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

To remove a lead 0b, you can simply take a substring bin(123)[2:].

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

New in version 2.6.

+7
source

bin() , . , .

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

Source: https://habr.com/ru/post/1736702/


All Articles