Python struct.pack和解压缩 [英] Python struct.pack and unpack

查看:60
本文介绍了Python struct.pack和解压缩的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我绝对不是一个经验丰富的python程序员,这就是为什么我相信可能对此有一个明显的答案,但是我只是无法将自己的头缠在struct.pack上并解包.我有以下代码:

Im in no way an experienced python programmer,thats why i believe there may be an obvious answer to this but i just can't wrap my head around the struct.pack and unpack. i have the following code:

struct.pack(<" +"I" * elements,* self.buf [:elements])

我想颠倒这个包装,但是我不确定如何,<"表示小尾数,"I"表示是unsigned int,仅此而已,我不确定如何使用struct.unpack来反转打包.

I want to reverse the the packing of this, however im not sure how, i know that "<" means little endian and "I" is unsigned int and thats about it, im not sure how to use struct.unpack to reverse the packing.

推荐答案

struct.pack 采用非字节值(例如,整数,字符串等)并将其转换为 bytes .相反, struct.unpack 占用 bytes 并将其转换为它们的高阶"等价物.

struct.pack takes non-byte values (e.g. integers, strings, etc.) and converts them to bytes. And conversely, struct.unpack takes bytes and converts them to their 'higher-order' equivalents.

例如:

>>> from struct import pack, unpack
>>> packed = pack('hhl', 1, 2, 3)
>>> packed
b'\x00\x01\x00\x02\x00\x00\x00\x03'
>>> unpacked = unpack('hhl', packed)
>>> unpacked
(1, 2, 3)

因此,在您的实例中,您具有低字节序的无符号整数(其中许多 elements 个元素).您可以使用相同的结构字符串('<'+'I'* elements 部分)对它们进行解压缩-例如 struct.unpack('<'+'I'*元素,值).

So in your instance, you have little-endian unsigned integers (elements many of them). You can unpack them using the same structure string (the '<' + 'I' * elements part) - e.g. struct.unpack('<' + 'I' * elements, value).

来自以下示例: https://docs.python.org/3/library/struct.html

这篇关于Python struct.pack和解压缩的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆