![](/img/trans.png)
[英]Reading a binary file in Python: takes a very long time to read certain bytes
[英]Python3 reading a binary file, 4 bytes at a time and xor it with a 4 byte long key
我想讀取二進制文件,獲取四個字節乘以四個字節的內容,並對這些數據包執行int操作。
使用虛擬二進制文件,以這種方式打開:
with open('MEM_10001000_0000B000.mem', 'br') as f:
for byte in f.read():
print (hex(byte))
我想用4字節長的密鑰執行加密,例如0x9485A347
。
有一種簡單的方法我可以一次讀取我的文件4個字節並將它們作為int或者我需要使用計數器將它們放入臨時結果嗎?
我最初的想法如下:
current_tmp = []
for byte in data:
current_tmp.append(int(byte))
if (len(current_tmp) == 4):
print (current_tmp)
# but current_tmp is an array not a single int
current_tmp = []
在我的例子,代替具有[132, 4, 240, 215]
我寧願有0x8404f0d7
只需使用read的“amount”參數一次讀取4個字節,然后使用Python的3 int
的“from_bytes”構造函數來實現它:
with open('MEM_10001000_0000B000.mem', 'br') as f:
data = f.read(4)
while data:
number = int.from_bytes(data, "big")
...
data = f.read(4)
如果由於某種原因你還沒有使用Python 3,那么int
將不會使用from_bytes
方法 - 那么你可以使用struct模塊:
import struct
...
number = struct.unpack(">i", data)[0]
...
然而,這些方法適用於幾個交互,並且對於大文件可能會變慢 - Python提供了一種方法,您可以直接從開放文件中直接在內存中填充4字節整數數組 - 這更可能是您應該的使用:
import array, os
numbers = array.array("i")
with open('MEM_10001000_0000B000.mem', 'br') as f:
numbers.fromfile(f, os.stat('MEM_10001000_0000B000.mem').st_size // numbers.itemsize)
numbers.byteswap()
一旦你有了數組,就可以用類似的東西對它進行xor
from functools import reduce #not needed in Python2.7
result = reduce(lambda result, input: result ^ input, numbers, key)
將為您提供一個numbers
序列,文件中的所有數字都以4字節,大端,有符號整數讀入。
如果你的文件不是4個字節的倍數,前兩個方法可能需要一些調整 - 修復while
條件就足夠了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.