Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading binary byte by byte in Ruby

Tags:

parsing

ruby

I'm currently trying to read a binary file in chunks, and my solution so far has been this:

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

Where the first number is the amount of bytes to read and the second is the offset.

I know this is bad because File.binread closes the file each time after returning. How can I open the file once, do what I with with is, then close it when I'm done (but still use binread).

Also, another small question. I've been looking at a few examples of this in python and seen this:

UINT32 = 'uintle:32'

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

What exactly is this doing (how does it work), and what would this look like in Ruby?

like image 611
Fianite Avatar asked Jun 06 '16 20:06

Fianite


1 Answers

You can open the file and read bytes in chunks with #read and #seek:

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

The file is closed automatically in the end.

About the second question, I'm not a Python expert, and someone correct me if I'm wrong, but it would be this in 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

You can check more options here: String#unpack

like image 138
Silver Phoenix Avatar answered Sep 27 '22 15:09

Silver Phoenix