Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python program to convert decimal to binary number
Converting decimal numbers to binary is a fundamental programming task. Python provides both manual and built-in approaches to achieve this conversion.
Problem Statement
Given a decimal number, we need to convert it into its binary representation.
Using Recursive Approach
The recursive method divides the number by 2 repeatedly and prints the remainders in reverse order −
Algorithm
DecToBin(num):
if num > 1:
DecToBin(num // 2)
print num % 2
Example
def DecimalToBinary(num):
if num > 1:
DecimalToBinary(num // 2)
print(num % 2, end='')
# Test the function
dec_val = 35
print("Binary representation of", dec_val, "is: ", end='')
DecimalToBinary(dec_val)
Binary representation of 35 is: 100011
Using Built-in bin() Function
Python's bin() function provides a direct way to convert decimal to binary −
def decimalToBinary(n):
return bin(n).replace("0b", "")
# Test the function
decimal_number = 35
binary_result = decimalToBinary(decimal_number)
print(f"Binary representation of {decimal_number} is: {binary_result}")
Binary representation of 35 is: 100011
Using format() Function
Another built-in approach uses the format() function with binary format specifier −
def decimalToBinaryFormat(n):
return format(n, 'b')
# Test the function
decimal_number = 35
binary_result = decimalToBinaryFormat(decimal_number)
print(f"Binary representation of {decimal_number} is: {binary_result}")
Binary representation of 35 is: 100011
Comparison
| Method | Complexity | Best For |
|---|---|---|
| Recursive | O(log n) | Understanding the algorithm |
| bin() function | O(1) | Quick conversion |
| format() function | O(1) | Clean, readable code |
Conclusion
Use bin() or format() for efficient built-in conversion. The recursive approach helps understand the mathematical process of decimal-to-binary conversion.
Advertisements
