如何将字节元组转换为整数并返回?

问题:我想得到


(7,5,3) => 000001110000010100000011 => 460035  

  also the converse, i.e.,   

460035 => 000001110000010100000011 => (7,5,3)

这是我尝试过的程序:


L=(7,5,3) # here L may vary each time.

a=0

for i in range(3):

    a=bin(a << 8) ^ bin(L[i])

print a  

但它给出了错误TypeError: unsupported operand type(s) for ^: 'str' and 'str'

我该怎么做?


守候你守候我
浏览 236回答 2
2回答

呼如林

没有必要重新发明轮子。如果您看到了我在评论中提供的文档链接,您可以在那里找到这些有用的方法:int.from_bytes和int.to_bytes.&nbsp;我们可以这样使用它们:input = (7, 5, 3)result = int.from_bytes(input, byteorder='big')print(result)>>> 460035print(tuple(result.to_bytes(3, byteorder='big')))>>> (7, 5, 3)

小怪兽爱吃肉

您应该对数字而不是转换后的字符串执行位操作:L=(7,5,3)a=0for i in L:&nbsp; &nbsp; a <<= 8&nbsp; &nbsp; a |= iprint(bin(a), a)这输出:0b1110000010100000011 460035逆转:a = 460035L = []while True:&nbsp; &nbsp; L.append(a & 0xff)&nbsp; &nbsp; a >>= 8&nbsp; &nbsp; if not a:&nbsp; &nbsp; &nbsp; &nbsp; breakL = tuple(L[::-1])print(L)这输出:(7, 5, 3)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python