8

I need to be able to parse a binary file with Ruby. This file contains chunks of data that are found via a header that includes the file offset and length of each chunk.

How do I get the data out correctly? I've been unable so far to seek around in the file based on the offsets I read out since they come out in strings that I don't know how to convert to a format IO#seek understands.

Any help? A general way to convert the offset and length into something usable (like an integer or something) would be helpful.

3 Answers 3

6

You want String#unpack.

Sign up to request clarification or add additional context in comments.

2 Comments

That was it. unpack('L*') is what I needed.
You should be explicitly using the little-endian or big-endian unpacks instead of native-endian, to keep a bit of portability.
2

You could also take a look at BitStruct which offers a nice high-level interface for parsing binary data.

Comments

2

Check out the BinData gem, and the alternatives it lists:

http://bindata.rubyforge.org/#alternatives

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.