我正在嘗試將二進制檔案加載到 numpy 并洗掉一些我不需要的不需要的值,然后重塑該陣列并使用它進行一些計算。
這是我的參考代碼:
def read_binary_data(filename, buffer_size):
np.set_printoptions(threshold=sys.maxsize)
np.set_printoptions(formatter={'int': hex})
with open(filename, "rb") as f:
binary_array = np.fromfile(f, dtype='B', offset=3)
print(binary_array)
結果如下:
...
0xff 0xff 0x0 0x0 0x0 0x0 0x4e 0x44 0x0 0x0 0x8 0x0 0x0 0x0 0xd2 0xf4
0xff 0xff 0x0 0x0 0x0 0x0 0x4e 0x44 0x0 0x0 0x8 0x0 0x0 0x0 0xd2 0xf4
0xff 0xff 0x0 0x0 0x0 0x0 0x4e 0x44 0x0 0x0 0x8 0x0 0x0 0x0 0xd2 0xf4
0xff 0xff 0x0 0x0 0x0 0x0 0x4e 0x44 0x0 0x0 0x8 0x0 0x0 0x0 0xd2 0xf4
0xff 0xff 0x0 0x0 0x0 0x0 0x4e 0x44 0x0 0x0 0x8 0x0 0x0 0x0 0xd2 0xf4
0xff 0xff 0x0 0x0 0x0 0x0 0x4e 0x44 0x0 0x0 0x8 0x0 0x0 0x0 0xd2 0xf4
0xff 0xff 0x0 0x0 0x0 0x0 0x4e 0x44 0x0 0x0 0x8 0x0 0x0 0x0 0xcf 0xf4
0xff 0xff 0x0 0x0 0x0 0x0]
比方說,我想洗掉所有出現的0x4e 0x44
但不是自己的,這是我感興趣的兩者的組合。因為如果說我有0x4e
我想保持這個完整。0x44
0x4e 0x54
我怎么能做到這一點?
感謝您的幫助
uj5u.com熱心網友回復:
謝謝大家的意見。
我想出了一種盡可能有效地實作這一目標的方法。可能有更好的方法來做到這一點,但現在這項作業:D
np.set_printoptions(formatter={'int': hex})
with open(filename, "rb") as f:
binary_array = np.fromfile(f, dtype='B')
# Clean array
to_remove = []
indexes = np.where(binary_array == 0x4e)
# find all occurences of 4E54
x54_mask = binary_array[indexes[0] 1] == 0x54
to_remove = [*to_remove, *list(indexes[0][x54_mask])]
# find all occurences of 4E53
x53_mask = binary_array[indexes[0] 1] == 0x53
to_remove = [*to_remove, *list(indexes[0][x53_mask])]
# removing unwanted values
to_remove_f = []
for i in to_remove:
to_remove_f.append(i)
to_remove_f.append(i 1)
binary_array = np.delete(binary_array, to_remove_f)
for 回圈僅用于僅包含 < 10 個值的“to_remove”串列。
和平:D
uj5u.com熱心網友回復:
請注意,僅僅因為您的陣列正在列印十六進制值,這些值本身仍然是整數。無論如何,這是查找和洗掉對的一種方法0x4e 0x44
,盡管可能不是最有效的:
indices_to_delete = []
for i in range(len(binary_array) - 1):
# Check if the current value and the one right after are a pair
# If so, they will need to be deleted
if binary_array[i] == int("0x4e", 0) and binary_array[i 1] == int("0x44", 0):
indices_to_delete = [i, i 1]
binary_array = np.delete(binary_array[None, :], indices_to_delete, axis=1)[0]
您的二進制陣列現在沒有 對,盡管or的0x4e 0x44
任何單數實體都被單獨留下。0x4e
0x44
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/463193.html