Q:

Python program to convert binary tuple to integer

belongs to collection: Python Tuple Programs

0

Example:

tuple = ("python", "includehelp", 43, 54.23)

Converting Binary Tuple to Integer

We are given a tuple consisting of only binary values (0 or 1). Using this tuple, we need to convert the tuple into an integer.

Input:
tup = (1, 0, 1, 1, 0)

Output:
22

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Method 1:

One method to solve the problem is by using the bitwise shift operator to left shift bits of the number and find the binary addition using the or operator to find the resulting value.

# Python program to convert Binary Tuple 
# to Integer value

# Creating and print the tuple 
myTuple = (1, 0, 1, 1, 0, 0, 1)
print("The tuple of binary values is " + str(myTuple))

# Converting the binary tuple to integer value
integerVal = 0
for val in myTuple:
	integerVal = (integerVal << 1) | val

# Printing the converted Integer value
print("Converted Integer value is " + str(integerVal))

Output:

The tuple of binary values is (1, 0, 1, 1, 0, 0, 1)
Converted Integer value is 89

Method 2:

Another method to solve the problem is by using list comprehension and formatting the binary values of the tuple using join() and str() methods.

After creating the string, we will convert it back to an integer using base 2.

# Python program to convert Binary Tuple 
# to Integer value

# Creating and print the tuple 
myTuple = (1, 0, 1, 1, 0, 0, 1)
print("The tuple of binary values is " + str(myTuple))

# Converting the binary tuple to integer value
integerVal = int("".join(str(vals) for vals in myTuple), 2)

# Printing the converted Integer value
print("Converted Integer value is " + str(integerVal))

Output:

The tuple of binary values is (1, 0, 1, 1, 0, 0, 1)
Converted Integer value is 89

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Tuple Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python program to convert tuple matrix to tuple li... >>
<< Python program to perform tuple intersection in li...