tags:

views:

73

answers:

3

Hello,

Is there any module or function in python i can use to convert a decimal number to its binary equivalent ? I am able to convert binary to decimal using int('[binary_value]',2),so any way to do the reverse without writing the code to do it myself ?

Thank You

+4  A: 

all numbers are stored in binary. if you want a textual representation of a given number in binary, use bin(i)

>>> bin(10)
'0b1010'
>>> 0b1010
10
aaronasterling
+1  A: 
"{0:#b}".format(my_int)
Matt Williamson
A: 

I agree with @aaronasterling's answer. However, if you want a non-binary string that you can cast into an int, then you can use the canonical algorithm:

def decToBin(n):
    if n==0: return ''
    else:
        return decToBin(n/2) + str(n%2)
inspectorG4dget
`int(bin(10), 2)` yields `10`. `int(decToBin(10))` yields `101` and `int(decToBin(10), 2)` yields 5. Also, your function hit's recursion limits with `from __future__ import division` or python 3
aaronasterling
@aaron, the latter point can be solved by switching to `//` (truncating division); the former, by switching the order of the two strings being summed in the `return`. Not that recursion makes any sense here anyway (`bin(n)[2:]` -- or a `while` loop if you're stuck on some old version of Python -- will be _much_ better!).
Alex Martelli