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?
166
votes
Unlike the linked question "convert to binary string", I think this question is different. I came here looking to convert an integer to a corresponding binary array (or boolean array), and I think that would be a sensible answer.
- Sanjay Manohar
@SanjayManohar The pure string processing algorithm found here could be adapted to do what you want.
- CopyPasteIt
8 Answers
266
votes
72
votes
Without the 0b in front:
"{0:b}".format(int)
Starting with Python 3.6 you can also use formatted string literal or f-string, --- PEP:
f"{int:b}"
16
votes
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.
12
votes
5
votes
2
votes
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.