[英]Python struct.pack and unpack
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.我绝不是一个有经验的 python 程序员,这就是为什么我相信这个问题可能有一个明显的答案,但我只是无法围绕 struct.pack 和解包。 i have the following code:
我有以下代码:
struct.pack("<"+"I"*elements, *self.buf[:elements])
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.我想反转这个包装,但是我不确定如何,我知道“<”表示小端,“I”是无符号整数,就是这样,我不确定如何使用 struct.unpack 来反转包装.
struct.pack
takes non-byte values (eg integers, strings, etc.) and converts them to bytes
. struct.pack
接受非字节值(例如整数、字符串等)并将它们转换为bytes
。 And conversely, struct.unpack
takes bytes
and converts them to their 'higher-order' equivalents.相反,
struct.unpack
接受bytes
并将它们转换为它们的“高阶”等价物。
For example:例如:
>>> 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)
So in your instance, you have little-endian unsigned integers ( elements
many of them).因此,在您的实例中,您有小端无符号整数(
elements
许多是elements
)。 You can unpack them using the same structure string (the '<' + 'I' * elements
part) - eg struct.unpack('<' + 'I' * elements, value)
.您可以使用相同的结构字符串(
'<' + 'I' * elements
部分)将它们解包 - 例如struct.unpack('<' + 'I' * elements, value)
。
Example from: https://docs.python.org/3/library/struct.html示例来自: https : //docs.python.org/3/library/struct.html
Looking at the documentation: https://docs.python.org/3/library/struct.html查看文档: https : //docs.python.org/3/library/struct.html
obj = struct.pack("<"+"I"*elements, *self.buf[:elements])
struct.unpack("<"+"I"*elements, obj)
Does this work for you?这对你有用吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.