ADVERTISEMENT
ADVERTISEMENT

Python program to convert binary tuple to integer

Here, we have a tuple consisting of only binary values and we need to convert the binary tuple to an Integer value.
Submitted by Shivang Yadav, on September 01, 2021

Python programming language is a high-level and object-oriented programming language. Python is an easy to learn, powerful high-level programming language. It has a simple but effective approach to object-oriented programming.

Tuples in Python is a collection of items similar to list with the difference that it is ordered and immutable.

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

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

Python Tuple Programs »



ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.