Skip to main content

How to convert a number from decimal to binary in Python

How to convert a number from decimal to binary in Python.

Here's a step-by-step tutorial on how to convert a number from decimal to binary in Python:

  1. Start by defining a function called decimal_to_binary that takes a decimal number as input.
  2. Inside the function, create an empty list called binary_digits to store the binary digits.
  3. Use a while loop to perform the binary conversion. The loop should continue as long as the decimal number is greater than 0.
  4. Inside the loop, use the modulo operator (%) to get the remainder when dividing the decimal number by 2. This remainder will be either 0 or 1, which represents the binary digit.
  5. Append the binary digit to the binary_digits list.
  6. Update the decimal number by performing integer division (//) with 2. This will effectively remove the least significant bit from the decimal number.
  7. After the loop finishes, reverse the binary_digits list using the reverse() method.
  8. Finally, join the binary digits in the binary_digits list using the join() method, passing an empty string as the separator. This will give you the binary representation as a string.
  9. Return the binary representation from the function.

Here's the code implementation:

def decimal_to_binary(decimal):
binary_digits = []

while decimal > 0:
binary_digits.append(decimal % 2)
decimal //= 2

binary_digits.reverse()
binary = ''.join(str(digit) for digit in binary_digits)
return binary

Now, you can use this function to convert decimal numbers to binary. Here are a few examples:

# Example 1: Convert decimal 10 to binary
binary_10 = decimal_to_binary(10)
print(binary_10) # Output: 1010

# Example 2: Convert decimal 42 to binary
binary_42 = decimal_to_binary(42)
print(binary_42) # Output: 101010

# Example 3: Convert decimal 255 to binary
binary_255 = decimal_to_binary(255)
print(binary_255) # Output: 11111111

That's it! You now have a function that can convert decimal numbers to binary in Python.