-1

So yeah I'm trying to figure a way on how to change a decimal into a binary in python

1
  • So you want to print an integer in binary? Commented Sep 11, 2013 at 17:31

2 Answers 2

3

How about bin:

>>> bin(42)
'0b101010'
Sign up to request clarification or add additional context in comments.

3 Comments

This wont work. Try bin(Decimal(10.9)) in python 2.x
@karthikr Indeed, bin is only for integers, as stated in the documentation. However, I don't think the OP referred to decimal.Decimal
there is no way to know that. :)
1
In [1]: def dec2bin(n):
   ...:     if not n:
   ...:         return ''
   ...:     else:
   ...:         return dec2bin(n/2) + str(n%2)
   ...:     

In [2]: dec2bin(11)
Out[2]: '1011'

2 Comments

Looks rather convoluted given that there are already standard functions to do just that.
@arshajii: Yeah, but I figured I'd give a DIY answer for completeness, just in case that's what OP was after

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.