簡體   English   中英

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的數字。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM