Convert decimal to binary in python

PythonBinaryDecimal

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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 - Python

"{0:#b}".format(my_int)

Solution 3 - Python

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 - Python

def dec_to_bin(x):
    return int(bin(x)[2:])

It's that easy.

Solution 5 - Python

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.

Solution 6 - Python

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)

Solution 7 - Python

n=int(input('please enter the no. in decimal format: '))
x=n
k=[]
while (n>0):
    a=int(float(n%2))
    k.append(a)
    n=(n-a)/2
k.append(0)
string=""
for j in k[::-1]:
    string=string+str(j)
print('The binary no. for %d is %s'%(x, string))

Solution 8 - Python

For the sake of completion: if you want to convert fixed point representation to its binary equivalent you can perform the following operations:

  1. Get the integer and fractional part.

     from decimal import *
     a = Decimal(3.625)
     a_split = (int(a//1),a%1)
     
    
  2. 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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPaulView Question on Stackoverflow
Solution 1 - PythonaaronasterlingView Answer on Stackoverflow
Solution 2 - PythonMatt WilliamsonView Answer on Stackoverflow
Solution 3 - Pythonuser136036View Answer on Stackoverflow
Solution 4 - PythonschmidmtView Answer on Stackoverflow
Solution 5 - PythonflonkView Answer on Stackoverflow
Solution 6 - PythoninspectorG4dgetView Answer on Stackoverflow
Solution 7 - PythonharryView Answer on Stackoverflow
Solution 8 - PythonKalousteView Answer on Stackoverflow