Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert decimal to binary in python [duplicate]

People also ask

How do you convert decimal to binary in Python?

In Python, we can simply use the bin() function to convert from a decimal value to its corresponding binary value. The bin() takes a value as its argument and returns a binary equivalent. Note: bin() return binary value with the prefix 0b, so depending on the use-case, formatting should be done to remove 0b.

How do you find the binary equivalent of a number in Python?

Use bin() Function to Convert Int to Binary in Python In Python, you can use a built-in function, bin() to convert an integer to binary. The bin() function takes an integer as its parameter and returns its equivalent binary string prefixed with 0b .


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

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

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}"

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

It's that easy.


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.

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)