How to Convert Decimal to Binary in Python



In this article, you will learn how to convert decimal to binary in Python.

Convert decimal to binary

To convert a decimal number to its binary equivalent in Python, you can use the built-in bin() function.

The bin() function takes an integer as an argument and returns a string representing the binary equivalent of that integer.

Here’s an example:

decimal_number = 13
binary_number = bin(decimal_number)


# Output: 0b1101

In this example, we convert the decimal number 13 to its binary equivalent using the bin() function. The resulting binary number is 0b1101.

Note that the 0b prefix in the output indicates that the number is in binary format.

If you want to remove the 0b prefix from the binary number, you can use string slicing:

binary_number = bin(decimal_number)[2:]

# Output: 1101

In this example, we slice the binary number starting from the 3rd character (index 2) to remove the 0b prefix. The resulting binary number is 1101.