  Python | Binary list to integer

Python Methods and Functions

Method # 1: Using join () + list comprehension
Combining the two can help accomplish this particular task. In this method, the entire list is first converted to a string, then converted to int, and then a binary number is obtained.

 # Python3 demo code # convert binary list to integer # using join () + list comprehension   # initializing list test_list = [ 1 , 0 , 0 , 1 , 1 , 0 ]   # print original list print ( "The original list is:" + str (test_list))    # using join () + list comprehension # converting a binary list to an integer res = int ("". join ( str (x) for x in test_list), 2 )   < code class = "comments"> # print result print ( "The converted integer value is:" +   str (res))

Output:

The original list is: [1, 0, 0, 1, 1, 0] The converted integer value is: 38

Method # 2: Using the bits Shift + | operator
This particular task can be accomplished by shifting bits and accepting | with each of the processed bits. This is another elegant way it can be accomplished.

 # Python3 demo code # convert binary list to integer # using bit shift + | statement   # initializing list test_list = [ 1 , 0 , 0 , 1 , 1 , 0 ]   # print original list print ( "The original list is:" + str (test_list))   # using bit shift + | statement # convert binary list to integer res = 0 for ele in test_list:   res = (res & lt; & lt; 1 ) | ele   # print result print ( "The converted integer value is:" +   str (res))

Output:

The original list is: [1, 0, 0 , 1, 1, 0] The converted integer value is: 38