Binary list to integer in Python

PythonServer Side ProgrammingProgramming

We can convert a list of 0s and 1s representing a binary number to a decimal number in python using various approaches. In the below examples we use the int() method as well as bitwise left shift operator.

Using int()

The int() method takes in two arguments and changes the base of the input as per the below syntax.

int(x, base=10)
Return an integer object constructed from a number or string x.

In the below example we use the int() method to take each element of the list as a string and join them to form a final string which gets converted to integer with base 10.

Example

 Live Demo

List = [0, 1, 0, 1, 0, 1]
print ("The List is : " + str(List))
# binary list to integer conversion
result = int("".join(str(i) for i in List),2)
# result
print ("The value is : " + str(result))

Running the above code gives us the following result −

The List is : [1, 1, 0, 1, 0, 1]
The value is : 53

Using the Bitwise Left Shift Operator

The bitwise left shift operator converts the given list of digits to an integer after adding to zeros to the binary form. Then bitwise or is used to add to this result. We use a for loop to iterate through each of the digits in the list.

Example

 Live Demo

List = [1, 0, 0, 1, 1, 0]
print ("The values in list is : " + str(List))

# binary list to integer conversion
result = 0
for digits in List:
result = (result << 1) | digits

# result
print ("The value is : " + str(result))

Running the above code gives us the following result −

The values in list is : [1, 0, 0, 1, 1, 0]
The value is : 38
raja
Published on 19-Dec-2019 15:40:41
Advertisements