0
使用我的代碼時出現以下錯誤。我的這個代碼的目標是創建一個類來將整數輸入轉換爲套接字消息的二進制數據。我試圖理解這個應用程序的打包和解包。任何幫助表示讚賞。Python結構/裝箱錯誤
代碼:
import struct
def BinaryPacker(input1):
s = struct.Struct('@I')
pack_data = s.pack(int(input1))
print 'Original values:', input1
print 'Format string :', s.format
print 'Uses :', s.size, 'bytes'
return pack_data
#BinaryUnpacker unpacks the data with small discrepancy in floating point value
def BinaryUnpacker(input2):
s = struct.Struct('@I')
print input2
print 'Size of struct: ', struct.calcsize(input2)
unpack_data = s.unpack(input2)
print 'Unpacked Values:', unpack_data
print unpack_data[0]
print '\n'
while True:
print ("Message to pack n unpack:")
message = raw_input()
message = BinaryPacker(message)
BinaryUnpacker(message)
錯誤1:對於使用小數目< 10出現某種原因雖然9似乎工作被解釋爲一個char而不是字符串。
Message to pack n unpack:
5
Original values: 5
Format string : @I
Uses : 4 bytes
Size of struct:
Traceback (most recent call last):
File "C:\PythonPractice\BinaryPacker.py", line 43, in <module>
BinaryUnpacker(message)
File "C:\PythonPractice\BinaryPacker.py", line 33, in BinaryUnpacker
print 'Size of struct: ', struct.calcsize(input2)
struct.error: bad char in struct format
錯誤2:如果我嘗試將input2轉換爲整數,我得到一個文字錯誤。
C:\PythonPractice>BinaryPacker.py
Message to pack n unpack:
9
Original values: 9
Format string : @I
Uses : 4 bytes
Size of struct:
Traceback (most recent call last):
File "C:\PythonPractice\BinaryPacker.py", line 43, in <module>
BinaryUnpacker(message)
File "C:\PythonPractice\BinaryPacker.py", line 33, in BinaryUnpacker
print 'Size of struct: ', struct.calcsize(int(input2))
ValueError: invalid literal for int() with base 10: ''
C:\PythonPractice>BinaryPacker.py
Message to pack n unpack:
10
Original values: 10
Format string : @I
Uses : 4 bytes
Size of struct:
Traceback (most recent call last):
File "C:\PythonPractice\BinaryPacker.py", line 43, in <module>
BinaryUnpacker(message)
File "C:\PythonPractice\BinaryPacker.py", line 33, in BinaryUnpacker
print 'Size of struct: ', struct.calcsize(int(input2))
ValueError: invalid literal for int() with base 10: ''