在 Ruby 中逐字节读取二进制

Fia*_*ite 5 ruby parsing

我目前正在尝试分块读取二进制文件,到目前为止我的解决方案是这样的:

first_portion = File.binread(replay_file, 20)
second_portion = File.binread(replay_file, 24, 20)
Run Code Online (Sandbox Code Playgroud)

其中第一个数字是要读取的字节数,第二个数字是偏移量。

我知道这很糟糕,因为 File.binread 每次返回后都会关闭文件。我如何打开文件一次,执行我的操作,然后在完成后关闭它(但仍然使用 binread)。

另外,还有一个小问题。我一直在 python 中查看一些这样的示例,并看到了以下内容:

UINT32 = 'uintle:32'

length = binary_file.read(UINT32)
content = binary_file.read(8 * length)
Run Code Online (Sandbox Code Playgroud)

它到底在做什么(它是如何工作的),在 Ruby 中会是什么样子?

Sil*_*nix 5

#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
Run Code Online (Sandbox Code Playgroud)

该文件在end.

关于第二个问题,我不是Python专家,如果我错了,有人会纠正我,但在Ruby中会是这样:

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
Run Code Online (Sandbox Code Playgroud)

您可以在此处查看更多选项:String#unpack