这种数据转换究竟是如何进行的?

How was this data conversion performed exactly?

所以,长话短说,我正在尝试自己 'unpack' 一些数据,但我做不到。幸运的是我有解决方案,但我想不出方法。基本上,我这里有这个数据数组,

[16 130 164 65 103 136 209 64 19 36 185 190 83]

,我被告知当通过 'fffB' 'unpacked' 时,我得到:

[ 20.56350708,   6.54790068,  -0.36160335,  83]

我知道这个解决方案是正确的,但我不确定我们是如何实现的。

这里的上下文是输入数组是 'unpacked',使用 Python 的命令是这样的:

struct.unpack_from('fffB', input)

虽然我尽力了,但我无法理解这里的确切操作。

首先您需要将数字列表转换为字符串,因为这是 unpack 所期望的:

Unpack from the buffer buffer (presumably packed by pack(fmt, ...)) according to the format string fmt. The result is a tuple even if it contains exactly one item. The buffer’s size in bytes must match the size required by the format, as reflected by calcsize().

列表中的数字可以用 chr 转换为字符,一旦你 join 它们在一起,你就有了可以提供给 unpack 的输入:

import struct

d = [16, 130, 164, 65, 103, 136, 209, 64, 19, 36, 185, 190, 83]
s = ''.join(chr(x) for x in d) # s = bytearray(d) on Python 3

struct.unpack('fffB', s) # (20.563507080078125, 6.547900676727295, -0.36160334944725037, 83)

格式字符串 fffB 告诉 unpack 提取三个每个 4 字节的浮点数和一个 1 字节大小的无符号字符。总共提取了 13 个字节,这与您的数据长度相匹配。格式字符的确切规范可以从 Python documentation.

中找到

请注意,上面的示例仅适用于 Python 2.x,在 Python 3.x 上,您需要将列表转换为 bytearray 而不是字符串。