将字节码字符串打包为struct为32位值

时间:2013-12-07 20:30:33

标签: python

我需要将一个输入的值打包到一个struct中,并将其打包为一个32位的#(unsigned int)。

示例输入是'\ x08 \ x08 \ x08 \ x08'

然而,这不起作用:

>>> s = struct.pack('I', '\x08\x08\x08\x08')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
struct.error: cannot convert argument to integer

我做错了什么?将其包装为int()不起作用:

>>> int('\x08\x08\x08\x08', 16)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 16: '\x08\x08\x08\x08'

我正在尝试构建一个在此之前和之后具有其他打包值的结构。例如,我想要

inp = '\x08\x08\x08\x08'
s = struct.pack('HHIH', 50, 100, inp, 100)

返回

'2\x00d\x00\x08\x08\x08\x08d\x00'

2 个答案:

答案 0 :(得分:1)

什么 - 完全 - 您想要作为输出吗? struct.pack()将返回(如果有效)字符串,就像您开始传入的字符串一样。 struct.unpack('I', '\x08\x08\x08\x08')返回元组(134744072,)。将其反馈回struct.pack(),然后返回您开始使用的字符串:

>>> import struct
>>> struct.unpack('I', '\x08\x08\x08\x08')
(134744072,)
>>> struct.pack('I', _[0])
'\x08\x08\x08\x08'

所有这些都按照记录和预期进行。所以请明确你想要的东西。

  

我可以做一些像struct.pack('H',somevalue)+这样的事情   '\ x08 \ x08 \ x08 \ x08'+ struct.pack('H',someothervalue)来制作   一个大结构?

也许。这取决于你没有拼写的内容,比如你是否使用struct自动插入填充字节(用于对齐)。如果您自己将字符串粘贴在一起,那么您有责任将其完成。

如果您确定要粘贴4字节字符串,则使用struct格式代码4s是一种更简单的方法。

答案 1 :(得分:0)

字符串'\ x08 \ x08 \ x08 \ x08'已经是整数的“压缩”表示。 如果你想将它转换为python整数,你应该尝试这个:

struct.unpack('I','\x08\x08\x08\x08')

当然,要注意字节顺序。