这个数据转换是如何精确执行的?

2024-10-02 16:29:35 发布

您现在位置:Python中文网/ 问答频道 /正文

所以,长话短说,我试图'解包'一些数据自己,但我不能这样做。幸运的是我有解决办法,但我想不出方法。基本上,我这里有一组数据

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

,我被告知,当通过'fffB'进行“解包”时,我得到:

[ 20.56350708,   6.54790068,  -0.36160335,  83]

我知道这个解决办法是正确的,但我不确定我们是怎么做到的

这里的上下文是输入数组是“解包”的,使用Python命令如下:

struct.unpack_from('fffB', input)

不管我怎么努力,我都不明白这里的确切操作


Tags: 数据方法from命令input数组structunpack
1条回答
网友
1楼 · 发布于 2024-10-02 16:29:35

首先,您需要将数字列表转换为字符串,因为^{}希望这样:

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().

列表中的数字可以转换为带有^{}的字符,一旦将它们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中找到

请注意,上面的示例仅适用于Python2.x,在Python3.x上,您需要将列表转换为^{},而不是字符串

相关问题 更多 >