3

In Ruby i do so

asd = 123
asd = '%b' % asd # => "1111011"
2
  • Duplicate: stackoverflow.com/questions/1993834/… Commented Mar 12, 2010 at 18:41
  • The "duplicate" is for Python 2.5. Languages constantly evolve, don't be too eager to post "duplicate" question links. Commented Mar 12, 2010 at 21:33

3 Answers 3

7

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

>>> '{:b}'.format(123)            #{0:b} in python 2.6
'1111011'
Sign up to request clarification or add additional context in comments.

4 Comments

Pretty cool! But it should be '{0:b}'.format(123), and it is for python version ≥ 2.6 only.
Great, it is that i find out.
@Oliver: comment says it. '{:b}' is python 2.7 and 3.1 version.
7

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.

3 Comments

You could also remove the leading '0b' by doing bin(123).strip('0b').
@Justin, you should use lstrip instead of strip as the latter will strip any 0s from the end of the string as well as the front (thereby changing the value). The slice is probably a better way to go, as it will only ever remove those two characters from the string.
@tgray Yes, I agree now that I have thought about it a little more.
0

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'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.