我正在尝试使用 python 与设备交谈。我收到了一个包含存储信息的字节元组。如何将数据转换为正确的值:
响应 = (0, 0, 117, 143, 6)
前 4 个值是 32 位 int,告诉我已经使用了多少字节,最后一个值是使用的百分比。
我可以将元组作为 response[0] 访问,但看不到如何将前 4 个值放入我需要的 int 中。
将,
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]]))
假设一个无符号整数。可能有更好的方法来进行解包的转换,使用 join 的列表理解只是我想出的第一件事。
编辑:另请参阅 ΤZΩΤZΙΟΥ's comment on this answer about endianness。
编辑#2:如果您也不介意使用数组模块,这里是一种替代方法,可以避免列表理解的需要。感谢@JimB指出 unpack 也可以对数组进行操作。
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,)
这看起来像是减少的工作!
您基本上需要的是一次移位一个字节,然后添加(添加)序列中的下一个字节。
a = (0, 0, 117, 143, 6)
reduce(lambda x, y: (x<<8) + y, a)
7704326
如何使用地图功能:
a = (0, 0, 117, 143, 6)
b = []
map(b.append, a)
另外,我不知道这是否是您正在寻找的:
response = (0, 0, 117, 143, 6)
response[0:4]