1
當我使用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轉換爲這個打包的結構,那麼我還需要在文件(打包)中寫入這個值有什麼替代方法?