在 Python 中打包和解压缩字节时出错



输入值后,我的代码出现错误(见下面的代码(。我可以打包位,但拆包不起作用。有什么建议吗?我不完全了解打包和解包,文档有点混乱。

import struct

#binaryadder - 
def binaryadder(input):
input = int(input)
d = struct.pack("<I", input)
print d
print type(d)
d = struct.unpack("<I",input)
print d 
#Test Pack 
count = 0
while True:
print "Enter input"
a = raw_input()
binaryadder(a)
count = count + 1
print "While Loop #%s finishedn" % count 

此代码在我输入字符串后回抛以下错误:

Enter input
900
ä
<type 'str'>
Traceback (most recent call last):
File "C:PythonPracticeBinarygenerator.py", line 25, in <module>
binaryadder(a)
File "C:PythonPracticeBinarygenerator.py", line 17, in binaryadder
d = struct.unpack("<I",input)
struct.error: unpack requires a string argument of length 4
d = struct.pack("<I", input)

这会将输入打包到一个字符串中;因此输入的数字900被打包到字符串'x84x03x00x00'中。

然后,过了一会儿,你这样做:

d = struct.unpack("<I",input)

现在,您尝试解压缩相同的输入,该输入仍900。显然,这是行不通的,因为您需要解压缩一个字符串。在您的情况下,您可能想打开d这是您之前打包的包装。所以试试这个:

unpacked_d = struct.unpack("<I", d)

然后,unpacked_d应包含input的数字。

最新更新