Open In App

Python | Decimal to binary list conversion

Improve
Improve
Like Article
Like
Save
Share
Report

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)


Output

The 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


Output

The 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))


Output

The 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.



Last Updated : 21 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads