📜  Python – 将二进制元组转换为整数

📅  最后修改于: 2022-05-13 01:55:09.755000             🧑  作者: Mango

Python – 将二进制元组转换为整数

给定二进制元组表示数字的二进制表示,转换为整数。

方法 #1:使用 join() + 列表理解 + int()

在此,我们使用 join() 和 str() 以字符串格式连接二进制元组,然后通过将基数设为 2 转换为整数。

Python3
# Python3 code to demonstrate working of 
# Convert Binary tuple to Integer
# Using join() + list comprehension + int()
  
# initializing tuple
test_tup = (1, 1, 0, 1, 0, 0, 1)
  
# printing original tuple
print("The original tuple is : " + str(test_tup))
  
# using int() with base to get actual number
res = int("".join(str(ele) for ele in test_tup), 2) 
  
# printing result 
print("Decimal number is : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Convert Binary tuple to Integer
# Using bit shift and | operator
  
# initializing tuple
test_tup = (1, 1, 0, 1, 0, 0, 1)
  
# printing original tuple
print("The original tuple is : " + str(test_tup))
  
  
res = 0
for ele in test_tup: 
      
    # left bit shift and or operator 
    # for intermediate addition
    res = (res << 1) | ele 
  
# printing result 
print("Decimal number is : " + str(res))


输出
The original tuple is : (1, 1, 0, 1, 0, 0, 1)
Decimal number is : 105

方法#2:使用位移和|运算符

在这种情况下,我们执行左移并使用或运算符来获得二进制加法,从而计算结果。

Python3

# Python3 code to demonstrate working of 
# Convert Binary tuple to Integer
# Using bit shift and | operator
  
# initializing tuple
test_tup = (1, 1, 0, 1, 0, 0, 1)
  
# printing original tuple
print("The original tuple is : " + str(test_tup))
  
  
res = 0
for ele in test_tup: 
      
    # left bit shift and or operator 
    # for intermediate addition
    res = (res << 1) | ele 
  
# printing result 
print("Decimal number is : " + str(res)) 
输出
The original tuple is : (1, 1, 0, 1, 0, 0, 1)
Decimal number is : 105