使用我的代码时出现以下错误。我的代码的目标是创建一个类,将整数输入转换为二进制数据以进行套接字消息传递。我正在尝试了解这个应用程序的打包和解包。任何帮助表示赞赏。
代码:
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似乎被解释为char而不是字符串,尽管9似乎有效。
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: ''
答案 0 :(得分:0)
sap.m.ScrollContainer
将格式字符串作为参数,而不是编码的字节对象。在您的情况下,struct.calcsize
。