Convert decimal to binary in python
586,050
Solution 1
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
Solution 2
"{0:#b}".format(my_int)
Solution 3
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}"
Solution 4
def dec_to_bin(x):
return int(bin(x)[2:])
It's that easy.
Solution 5
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.
Related videos on Youtube
Author by
Paul
Updated on September 24, 2021Comments
-
Paul over 2 years
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?
-
Sanjay Manohar over 4 yearsUnlike 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.
-
CopyPasteIt about 4 years@SanjayManohar The pure string processing algorithm found here could be adapted to do what you want.
-
-
aaronasterling over 13 years
int(bin(10), 2)
yields10
.int(decToBin(10))
yields101
andint(decToBin(10), 2)
yields 5. Also, your function hit's recursion limits withfrom __future__ import division
or python 3 -
Alex Martelli over 13 years@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 thereturn
. Not that recursion makes any sense here anyway (bin(n)[2:]
-- or awhile
loop if you're stuck on some old version of Python -- will be much better!). -
Eric over 11 years-1 - don't return an int. Also,
dec_to_bin(-1)
givesValueError: invalid literal for int() with base 10: 'b1'
-
Waldo Bronchart about 11 yearsHere's the format for printing with leading zero's:
"{0:08b}".format(my_int)
-
Patrick Ferreira about 10 yearscan you explain that [2:] ?
-
leewz about 10 yearsTry
bin(2)
. You don't get '10'. You get '0b10'. Same possible pit withhex(2)
('0x2'). So you want all but the first two characters. So you take a slice that starts after the first two characters. -
Aziz Alto almost 9 yearsThis is awesome! it could go with the lambda way too :]
binary = lambda n: '' if n==0 else binary(n/2) + str(n%2)
-
Right leg about 6 yearsI got the following error:
TypeError: non-empty format string passed to object.__format__
-
Timo about 6 years@AzizAlto I get a busload full of numbers with lots of
e-
, also in the recursive call dectobin. -
Aziz Alto about 6 years@Timo lol apparently you are using Python3 just change
binary(n/2)
tobinary(n//2)
then you won't get that busload :-) -
Walter about 6 years@zero_cool if test_var = "Hello world" then test_var[2:] = "llo world"
-
Josef Klotzner over 4 yearssame for me with python 3.5.2 TypeError: non-empty format string passed to object.__format__ ahh - now i got it, what you meant: ```>>> "{0:b}".format(47) ---> '101111'
-
Wallace over 4 years@Eric could you explain why you shouldn't return an int??
-
Eric over 4 years@Wallace: because binary and decimal are a choice of how to show the number, not part of the number itself.
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
. -
Alexandre Allegro about 4 years@WaldoBronchart thats cool. Can you explain to me how does that work, having the leading zeros? Is that inbuilt, that you get the leading zeros with 0+8 or 0+16?
-
Darina Sergeivna over 3 yearsYou also can determine amount of bits that it will be represented in this way:>>>
"{:0>15b}".format(3)
>>> '000000000000011' -
hiperbolt over 3 yearsMisleading. bin() returns binary string, not binary
-
Chenying Gao almost 3 yearsTypeError: 'float' object cannot be interpreted as an integer
-
Gulzar almost 3 years@hiperbolt could use a link to a non-misleading solution
-
Arye P. almost 2 yearscan also
format(int_value, 'b')