Python 中的错误打包和解包字节

Error Packing and Unpacking bytes in 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 finished\n" % count 

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

Enter input
900
ä
<type 'str'>
Traceback (most recent call last):
  File "C:\PythonPractice\Binarygenerator.py", line 25, in <module>
    binaryadder(a)
  File "C:\PythonPractice\Binarygenerator.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 被打包到字符串 '\x84\x03\x00\x00'.

然后,稍后,您执行此操作:

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

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

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

unpacked_d 应该包含 input.

的数字