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?
8 Answers
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
Without the 0b in front:
"{0:b}".format(int_value)
Starting with Python 3.6 you can also use formatted string literal or f-string, --- PEP:
f"{int_value:b}"
5 Comments
TypeError: non-empty format string passed to object.__format__"{:0>15b}".format(3) >>> '000000000000011'format(int_value, 'b')"{0:#b}".format(my_int)
3 Comments
"{0:08b}".format(my_int)def dec_to_bin(x):
return int(bin(x)[2:])
It's that easy.
7 Comments
dec_to_bin(-1) gives ValueError: invalid literal for int() with base 10: 'b1'bin(2). You don't get '10'. You get '0b10'. Same possible pit with hex(2) ('0x2'). So you want all but the first two characters. So you take a slice that starts after the first two characters.dec_to_bin(0b101) == 101, which is nonsense because none of operations you can apply to 101 have any relation to the original 5 - for instance, dec_to_bin(0b101) + 1 == 102.You can also use a function from the numpy module
from numpy import binary_repr
which can also handle leading zeros:
Definition: binary_repr(num, width=None)
Docstring:
Return the binary representation of the input number as a string.
This is equivalent to using base_repr with base 2, but about 25x
faster.
For negative numbers, if width is not given, a - sign is added to the
front. If width is given, the two's complement of the number is
returned, with respect to that width.
Comments
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)
6 Comments
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// (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!).binary = lambda n: '' if n==0 else binary(n/2) + str(n%2)e-, also in the recursive call dectobin.binary(n/2) to binary(n//2) then you won't get that busload :-)For the sake of completion: if you want to convert fixed point representation to its binary equivalent you can perform the following operations:
Get the integer and fractional part.
from decimal import * a = Decimal(3.625) a_split = (int(a//1),a%1)Convert the fractional part in its binary representation. To achieve this multiply successively by 2.
fr = a_split[1] str(int(fr*2)) + str(int(2*(fr*2)%1)) + ...
You can read the explanation here.
int('[binary_value]',2)": no you aren't. That converts a string representation of binary to integer, and most probably what you are really looking for is the reverse. Decimal has nothing to do with it either way. Computers store numbers in binary.