为什么某些值会使struct.pack和struct.unpack在Windows上失败?
问题描述:
当我使用struct.pack()
将python整数转换为C结构(并将其写入文件),然后使用struct.unpack()
来反转转换时,我通常会得到原始值...但并非总是如此。为什么?有一些难以管理的价值吗?为什么某些值会使struct.pack和struct.unpack在Windows上失败?
实施例:
import struct
fileName ='C:/myFile.ext'
formatCode = 'H'
nBytes = 2
tries = range(8,12)
for value in tries:
newFile = open(fileName, mode='w+')
myBinary = struct.pack(formatCode, value)
newFile.write(myBinary)
newFile.close()
infile = open(fileName,'rb')
bytesRead = infile.read(nBytes)
newValue = struct.unpack(formatCode, bytesRead)
print value, 'equal', newValue[0]
infile.close()
回报:
8 equal 8
9 equal 9
10 equal 2573
11 equal 11
12 equal 12
它不仅发生与整数(2个字节:格式 'H'),而且还与其他类型和值。如果我将数据打包为整数,但不是浮点数,则值10会给出此“错误”,但使用浮点数时,我会收到其他值的错误。
如果问题是我不能将int数字10转换为这个打包的结构,那么我还需要在文件(打包)中写入这个值有什么替代方法?
答
写入时忘记指定二进制模式。 wb+
不是w+
。