Python Program to Convert Decimal to Binary (Using Bitwise Operator, Array, Function, and Recursion)
Introduction
Decimal and binary are two fundamental number systems in computing. While decimal is commonly used by humans, binary is the language of machines.
In this tutorial, we will explore multiple methods to perform decimal to binary conversion in Python, using various techniques like bitwise operators, arrays (lists), functions, and recursion.
Problem Statement
Write a Python program to convert a decimal number into binary using different approaches: bitwise operations, array/list manipulation, user-defined functions, and recursion.
Use Cases
-
Understanding how data is represented at the hardware level
-
Essential in networking (IP addressing, subnetting)
-
Required in competitive programming and algorithms
-
Useful in embedded systems and control systems
Method 1: Using Bitwise Operator
# Class for Decimal to Binary conversion using bitwise operators
class W3CW:
@staticmethod
def convert_using_bitwise(num):
if num == 0:
return "0"
binary = ""
for i in range(31, -1, -1):
k = num >> i
if (k & 1):
binary += "1"
elif binary:
binary += "0"
return binary
# Main execution
num = 10
print("Binary:", W3CW.convert_using_bitwise(num))
Output
Binary: 1010
Explanation:
-
The number is right-shifted and masked with
1
to extract bits. -
Leading zeros are ignored using a string condition.
Method 2: Using List (Array-like structure)
# Python Program to Convert Decimal to Binary Using List (Array-like structure)
class W3CW:
@staticmethod
def convert_using_list(num):
if num == 0:
return "0"
binary = []
while num > 0:
binary.append(str(num % 2))
num //= 2
return ''.join(reversed(binary))
num = 10
print("Binary:", W3CW.convert_using_list(num))
Explanation:
-
Remainders are stored in a list and reversed.
-
List simulates array behavior as in other languages.
Method 3: Using Function
# Python Program to Convert Decimal to Binary Using Function
class W3CW:
@staticmethod
def convert_to_binary(num):
if num == 0:
return "0"
result = ""
while num > 0:
result = str(num % 2) + result
num //= 2
return result
num = 10
print("Binary:", W3CW.convert_to_binary(num))
Explanation:
-
The function builds the binary string by prepending digits.
-
Modular and reusable for multiple inputs.
Method 4: Using Recursion
# Python Program to Convert Decimal to Binary Using Recursion
class W3CW:
@staticmethod
def convert_recursive(num):
if num == 0:
return ""
return W3CW.convert_recursive(num // 2) + str(num % 2)
num = 10
binary = W3CW.convert_recursive(num)
print("Binary:", binary if binary else "0")
Explanation:
-
Recursive calls build binary in correct order during return phase.
-
Base case is when number reaches zero.
Output of All Methods
For input 10
, the binary representation will be:
Binary: 1010