### Python - Convert Decimal to Binary Example

In this source code example, we will write a code to convert a decimal number to its binary equivalent in Python.

# Python - Convert Decimal to Binary Example

``````# Function to convert a Decimal Number to a Binary Number.

def decimal_to_binary(num: int) -> str:

if isinstance(num, float):
raise TypeError("'float' object cannot be interpreted as an integer")
if isinstance(num, str):
raise TypeError("'str' object cannot be interpreted as an integer")

if num == 0:
return "0b0"

negative = False

if num < 0:
negative = True
num = -num

binary: list[int] = []
while num > 0:
binary.insert(0, num % 2)
num >>= 1

if negative:
return "-0b" + "".join(str(e) for e in binary)

return "0b" + "".join(str(e) for e in binary)

if __name__ == "__main__":

# Convert an Integer Decimal Number to a Binary Number as str.
print(decimal_to_binary(0))

print(decimal_to_binary(2))

print(decimal_to_binary(7))

print(decimal_to_binary(35))

# negatives work too
print(decimal_to_binary(-2))
'-0b10'
``````

Output:

``````0b0
0b10
0b111
0b100011
-0b10``````

# Free Spring Boot Tutorial - 5 Hours Full Course

Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course