2016-06-06 56 views
2
字節的二進制字節

我目前正在試圖讀取數據塊的二進制文件,和我的解決方案,到目前爲止一直是這個:讀出由紅寶石

first_portion = File.binread(replay_file, 20) 
second_portion = File.binread(replay_file, 24, 20) 

其中第一個數字是要讀取的字節量第二個是偏移量。

我知道這是不好的,因爲每次返回後File.binread都會關閉文件。我怎樣才能打開這個文件,完成我的工作,然後在完成時關閉它(但仍然使用binread)。

另外,還有一個小問題。我一直在尋找的這Python中的幾個例子,也看到了:

UINT32 = 'uintle:32' 

length = binary_file.read(UINT32) 
content = binary_file.read(8 * length) 

到底這是什麼做什麼(它是如何工作的),什麼會這樣看起來像Ruby的?

回答

3

您可以打開該文件,並與#read#seek閱讀大塊字節:

File.open(replay_file) do |file| 
    first_portion = file.read(20) 
    file.seek(24, IO::SEEK_END) 
    second_portion = file.read(20) 
end 

該文件在end自動關閉。

關於第二個問題,我不是一個Python的專家,有人糾正我,如果我錯了,但它會在這個紅寶石:

length = binary_file.read(4).unpack('N').first 
# 32 bits = 4 bytes 
# i.e., read 4 bytes, convert to a 32 bit integer, 
# fetch the first element of the array (unpack always returns an array) 

content = binary_file.read(8 * length) 
# pretty much verbatim 

你可以在這裏查看更多選項:String#unpack

+0

謝謝,你一直非常有幫助。 – Fianite

+0

一個簡單的問題,如果我正在處理UINT64或FLOAT32,第二個答案中的第一行如何改變? UINT64將是8個字節,FLOAT32將是4個字節,是所有變化?另外,爲什麼第一次需要? – Fianite

+0

@Fianite'unpack'有更多選擇。閱讀它。 – tadman