Program for Decimal to Binary Conversion in Python
Decimal to Binary Conversion
Converting a decimal number to binary involves representing the number in base-2, where each digit is either 0 or 1.
We will explore three methods to perform this conversion using Python programming.
Method 1: Using Built-in Function
We use Python's built-in bin() function to convert a decimal number to binary.
def decimal_to_binary_builtin(n): return bin(n)[2:] num = int(input("Enter a decimal number: ")) print("Binary:", decimal_to_binary_builtin(num))
Method 2: Using Division by 2
We repeatedly divide the number by 2 and store the remainder.
def decimal_to_binary_division(n): binary = "" while n > 0: binary = str(n % 2) + binary n //= 2 return binary or "0" num = int(input("Enter a decimal number: ")) print("Binary:", decimal_to_binary_division(num))
Method 3: Using Recursion
We use recursion to keep dividing the number by 2 until it becomes 0, printing the remainder in reverse order.
def decimal_to_binary_recursive(n): if n == 0: return "" return decimal_to_binary_recursive(n // 2) + str(n % 2) num = int(input("Enter a decimal number: ")) print("Binary:", decimal_to_binary_recursive(num) or "0")