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 the binary tuples in string format using join() and str(), then convert to integer by mentioning base as 2.
Python3
# Python3 code to demonstrate working of# Convert Binary tuple to Integer# Using join() + list comprehension + int()# initializing tupletest_tup = (1, 1, 0, 1, 0, 0, 1)# printing original tupleprint("The original tuple is : " + str(test_tup))# using int() with base to get actual numberres = int("".join(str(ele) for ele in test_tup), 2)# printing resultprint("Decimal number is : " + str(res)) |
Output
The original tuple is : (1, 1, 0, 1, 0, 0, 1) Decimal number is : 105
Method #2: Using bit shift and | operator
In this we perform left bit shift and use or operator to get binary addition and hence compute the result.
Python3
# Python3 code to demonstrate working of# Convert Binary tuple to Integer# Using bit shift and | operator# initializing tupletest_tup = (1, 1, 0, 1, 0, 0, 1)# printing original tupleprint("The original tuple is : " + str(test_tup))res = 0for ele in test_tup: # left bit shift and or operator # for intermediate addition res = (res << 1) | ele# printing resultprint("Decimal number is : " + str(res)) |
Output
The original tuple is : (1, 1, 0, 1, 0, 0, 1) Decimal number is : 105
Method #3 : Using list(),map(),join(),int() methods
Python3
# Python3 code to demonstrate working of# Convert Binary tuple to Integer# initializing tupletest_tup = (1, 1, 0, 1, 0, 0, 1)# printing original tupleprint("The original tuple is : " + str(test_tup))# using int() with base to get actual numberx = list(map(str, test_tup))x = "".join(x)res = int(x, 2)# printing resultprint("Decimal number is : " + str(res)) |
Output
The original tuple is : (1, 1, 0, 1, 0, 0, 1) Decimal number is : 105
Method #4: Using for loop
Python3
# Python3 code to demonstrate working of# Convert Binary tuple to Integer# initializing tupletest_tup = (1, 1, 0, 1, 0, 0, 1)# printing original tupleprint("The original tuple is : " + str(test_tup))res = 0j = 0for i in range(len(test_tup), 0, -1): x = 2**j res += x*test_tup[i-1] if(j > len(test_tup)): break j += 1# printing resultprint("Decimal number is : " + str(res)) |
Output
The original tuple is : (1, 1, 0, 1, 0, 0, 1) Decimal number is : 105
Method: Using pow() function
Python3
binary_tuple = (1, 1, 0)result = 0length = len(binary_tuple)for i in range(length): element = binary_tuple[length - i - 1] result = result + element*pow(2, i)print("The output integer is:", result) |
Output
The output integer is: 6


