Python | Decimal to binary list conversion
Last Updated :
21 Apr, 2023
The conversion of a binary list to a decimal number has been dealt in a previous article. This article aims at presenting certain shorthand to do the opposite, i.e binary to decimal conversion. Let's discuss certain ways in which this can be done.
Method #1 : Using list comprehension + format() In this method, the conversion of the decimal to binary is handled by the format function. The logic of conversion to the list is done by the list comprehension function.
Python3
# Python3 code to demonstrate
# decimal to binary number conversion
# using format() + list comprehension
# initializing number
test_num = 38
# printing original number
print ("The original number is : " + str(test_num))
# using format() + list comprehension
# decimal to binary number conversion
res = [int(i) for i in list('{0:0b}'.format(test_num))]
# printing result
print ("The converted binary list is : " + str(res))
Output:The original number is : 38
The converted binary list is : [1, 0, 0, 1, 1, 0]
Method #2 : Using bin() + list comprehension The inbuilt function bin performs the function of conversion to binary and the list comprehension handles the logic to convert the binary number to the list.
Python3
# Python3 code to demonstrate
# decimal to binary number conversion
# using bin() + list comprehension
# initializing number
test_num = 38
# printing original number
print ("The original number is : " + str(test_num))
# using bin() + list comprehension
# decimal to binary number conversion
res = [int(i) for i in bin(test_num)[2:]]
# printing result
print ("The converted binary list is : " + str(res))
Output:The original number is : 38
The converted binary list is : [1, 0, 0, 1, 1, 0]
Method #3 : Using while
to convert a decimal number to a binary list in Python is to use bit manipulation operations to extract the binary digits from the decimal number and append them to a list.
Python3
decimal_num = 38
# Initialize an empty list to hold the binary digits
binary_list = []
# Extract the binary digits using bit manipulation
while decimal_num > 0:
binary_list.append(decimal_num % 2)
decimal_num //= 2
# Reverse the order of the binary digits in the list
binary_list.reverse()
# Print the original number and the converted binary list
print("The original number is :", decimal_num)
print("The converted binary list is :", binary_list)
OutputThe original number is : 0
The converted binary list is : [1, 0, 0, 1, 1, 0]
Time complexity: O(log N)
Auxiliary Space: O(log N)
Method #4: Using Recursion:
Algorithm:
1.Start with a non-negative decimal number n.
2.If n is 0, return an empty list, as there are no binary digits to represent 0.
3.Otherwise, divide n by 2 using integer division // to get the quotient q and the remainder r.
4.Call the dec_to_bin function recursively with q as the input, and append the remainder r to the result.
5.The base case of n being 0 will eventually be reached, at which point an empty list will be returned.
6.As the recursive calls return, the remainders are accumulated in the result list, representing the binary digits of n.
7.Once the final recursive call returns, the result list contains the binary representation of n, with the least significant digit at the end of the list.
8.Return the result list.
Python3
def dec_to_bin(n):
"""
Convert a decimal number to binary using recursion.
Parameters:
n (int): A non-negative decimal number to be converted to binary.
Returns:
list: A list of binary digits (0 or 1) representing the binary equivalent of n.
"""
# base case: if n is 0, return an empty list
if n == 0:
return []
# recursive case: divide n by 2 and call the function with the quotient,
# then append the remainder (which is either 0 or 1) to the result
else:
return dec_to_bin(n // 2) + [n % 2]
# example usage
test_num = 38
# print the original number
print("The original number is:", test_num)
# convert the number to binary using the dec_to_bin function
binary_list = dec_to_bin(test_num)
# print the result
print("The converted binary list is:", binary_list)
#This code is contributed by Jyothi pinjala
OutputThe original number is: 38
The converted binary list is: [1, 0, 0, 1, 1, 0]
Time Complexity:
The time complexity of this algorithm is O(log n), where n is the decimal input number. The algorithm repeatedly divides the input by 2 and the number of times it can be divided before reaching the base case of 0 is proportional to the logarithm of the input.
Space Complexity:
The space complexity of this algorithm is also O(log n), as the size of the recursive call stack is proportional to the number of times the input can be divided by 2 before reaching the base case.
Method #5: Using bitwise operators
Step by step approach:
Initialize a variable "result" to an empty list.
Create a variable "bit" and set it equal to 1.
Loop until the test_num becomes 0.
Within the loop, use bitwise AND operator (&) to check if the rightmost bit of test_num is 1.
If the result of the bitwise AND operation is 1, append 1 to the "result" list. Otherwise, append 0.
Shift the bits of test_num to the right by 1 using the bitwise right shift operator (>>).
Double the value of "bit" using the bitwise left shift operator (<<).
Once the loop is complete, reverse the "result" list to get the binary representation of the decimal number.
Print the binary representation.
Python3
# Python3 code to demonstrate
# decimal to binary number conversion
# using bitwise operators
# initializing number
test_num = 38
# printing original number
print("The original number is : " + str(test_num))
# using bitwise operators
# decimal to binary number conversion
result = []
bit = 1
while test_num > 0:
if test_num & 1:
result.append(1)
else:
result.append(0)
test_num = test_num >> 1
bit = bit << 1
result.reverse()
# printing result
print("The converted binary list is : " + str(result))
OutputThe original number is : 38
The converted binary list is : [1, 0, 0, 1, 1, 0]
Time complexity: O(log n) - where n is the decimal number.
Auxiliary space: O(log n) - this is the space required to store the binary representation of the decimal number.
Similar Reads
Python Program to Convert Binary to Hexadecimal
Given a binary number, the task is to write a Python program to convert the given binary number into an equivalent hexadecimal number. i.e convert the number with base value 2 to base value 16. In hexadecimal representation we 16 values to represent a number. Numbers 0-9 are expressed by digits 0-9
4 min read
Python - Binary list to integer
A binary list represents binary digits (0s and 1s) as individual elements of a list. This article will explore various methods to convert a binary list into an integer.Using int() with String ConversionThis is the most efficient method. By joining the binary list into a string and using the built-in
3 min read
Convert Decimal to Binary Number
The task of converting a decimal number to binary in Python involves representing the number in base-2 format, where each digit is either 0 or 1. For example, the decimal number 17 can be converted into binary, resulting in a binary representation like 10001.Using bitwise operatorThis method efficie
3 min read
Python - Ways to convert hex into binary
We are given a hexadecimal number we need to convert it to binary. For example a = "1A3" we need to convert it to binary so that resultant output should be 110100011.Using bin() and int()We can convert hexadecimal to binary by first converting it to an integer using int() and then using the bin() fu
1 min read
Convert Floating to Binary - Python
The task of converting a floating-point number to its binary representation in Python involves representing the number in the IEEE 754 format, which consists of a sign bit, an exponent and a mantissa. For example, given the floating-point number 10.75, its IEEE 754 32-bit binary representation is "0
3 min read
How to Convert Binary Data to Float in Python?
We are given binary data and we need to convert these binary data into float using Python and print the result. In this article, we will see how to convert binary data to float in Python. Example: Input: b'\x40\x49\x0f\xdb' <class 'bytes'>Output: 3.1415927410125732 <class 'float'>Explana
2 min read
Python - Convert Float to digit list
We are given a floating-point number and our task is to convert it into a list of its individual digits, ignoring the decimal point. For example, if the input is 45.67, the output should be [4, 5, 6, 7].Using string manipulationIn this method, the number is converted to a string and then each charac
4 min read
Python List Inversions
Sometimes, while programming, we have a problem in which we might need to perform certain bitwise operations among list elements. This is an essential utility as we come across bitwise operations many times. Letâs discuss certain ways in which this task can be performed. List Inversions using map()
4 min read
Python - Convert Binary tuple to Integer
Given Binary Tuple representing binary representation of a number, convert to integer. Input : test_tup = (1, 1, 0) Output : 6 Explanation : 4 + 2 = 6. Input : test_tup = (1, 1, 1) Output : 7 Explanation : 4 + 2 + 1 = 7. Method #1 : Using join() + list comprehension + int() In this, we concatenate t
5 min read
Python - List of float to string conversion
When working with lists of floats in Python, we may often need to convert the elements of the list from float to string format. For example, if we have a list of floating-point numbers like [1.23, 4.56, 7.89], converting them to strings allows us to perform string-specific operations or output them
3 min read