2011-10-04 118 views
5

我有一個奇怪的模式編碼的文件。例如,文件沒有正確解碼

Char(1字節)|整數(4字節)|雙(8字節)|等等...

到目前爲止,我寫了下面的代碼,但我一直無法弄清楚爲什麼仍然在屏幕上顯示垃圾。任何幫助將不勝感激。

BRK_File = 'commands.BRK' 
input = open(BRK_File, "rb") 

rev = input.read(1) 
filesize = input.read(4) 
highpoint = input.read(8) 
which = input.read(1) 

print 'Revision: ', rev 
print 'File size: ', filesize 
print 'High point: ', highpoint 
print 'Which: ', which 

while True 
    opcode = input.read(1) 
    print 'Opcode: ', opcode 
    if opcode = 120: 
     break 
    elif 
     #other opcodes 

回答

6

read()返回一個字符串,您需要解碼才能獲取二進制數據。您可以使用struct模塊進行解碼。

東西沿着以下行應該做的伎倆:

import struct 
... 
fmt = 'cid' # char, int, double 
data = input.read(struct.calcsize(fmt)) 
rev, filesize, highpoint = struct.unpack(fmt, data) 

您可能需要處理字節排列順序問題,但struct使得該pretty easy

+0

我相信最後一個字段是char:'fmt ='cidc'' –

+0

@StevenRumbalski:這不是一個完整的例子。只是顯示這個想法... – NPE

+0

太棒了。感謝你的回答。另外,我是Python的新手,如果你能進一步研究他的觀察,我將不勝感激。 – Peretz

0

顯示文件的內容以及輸出的「垃圾」會有幫助。

input.read()返回一個字符串,所以你必須將你正在閱讀的內容轉換爲你想要的類型。我建議看看struct模塊。