我正在尝试使用Python与设备通信。我得到了一个包含存储信息的字节元组。如何将数据转换为正确的值:
response = (0, 0, 117, 143, 6)
前4个值是32位整数,告诉我已经使用了多少字节,最后一个值是使用的百分比。
我可以通过response [0]访问元组,但不知道如何将前4个值转换为所需的整数。
请问,
num = (response[0] << 24) + (response[1] << 16) + (response[2] << 8) + response[3]
您可能需要使用struct模块,例如:
import struct
response = (0, 0, 117, 143, 6)
struct.unpack(">I", ''.join([chr(x) for x in response[:-1]]))
import struct
from array import array
response = (0, 0, 117, 143, 6)
bytes = array('B', response[:-1])
struct.unpack('>I', bytes)
好的,您没有指定字节序或整数是否为有符号的,也许使用struct模块更快,但以下是一种可能更简单的方法:
b = (8, 1, 0, 0)
sum(b[i] << (i * 8) for i in range(4))
import struct
from array import array
response = (0, 0, 117, 143, 6)
a = array('B', response[:4])
struct.unpack('>I', a)
(30095L,)
这看起来需要使用reduce函数!
基本上你需要做的是,每次按位移动一个字节,然后将序列中的下一个字节加上(加法)。
a = (0, 0, 117, 143, 6)
reduce(lambda x, y: (x<<8) + y, a)
7704326
a
更改为a[:4]
,代码就可以按照OP所需的方式正常工作(至少如果是大端)。没有必要直接点踩。 - Elmar Zander使用map函数怎么样:
a = (0, 0, 117, 143, 6)
b = []
map(b.append, a)
另外,我不知道这是否符合您的要求:
response = (0, 0, 117, 143, 6)
response[0:4]