From: "Simon Kröger" Date: 2006-07-18T05:37:43+09:00 Subject: Re: How can I parse binary files? ara.t.howard@noaa.gov wrote: > On Tue, 18 Jul 2006, Fabio Vitale wrote: > >> Daniel Martin wrote: >>> Fabio Vitale writes: >>> >>>> I've the need to parse a binary file with the following structure: >>>> How can I accomplish this in Ruby? >>> >> require 'bit-struct' >> >> class MRK < BitStruct >> unsigned :version, 4, "Version" >> unsigned :uid_Validity, 4, "UIDValidity" >> unsigned :uid_next, 4, "UIDNext" >> unsigned :last_write_counter, 4, "LastWriteCounter" >> rest :unused, "Unused" >> end >> >> mrk = MRK.new >> >> And now: how to populate the mrk instance just created from the imap.mrk >> binary file? > > without even looking at the docs i'd guess you could do > > data = IO.read 'your.data' > > mrk = MRK.new data > > > and, indeed, this seems to work: > > [snip] This looks like a nice way. I just wanted to show that in such a simple case unpack isn't that ugly, too. open('file.bin', 'rb').do |f| version, uidValid, uidNext, lwCounter = f.read(36).unpack('IIII') name, flags, uid, size, date = f.read(36).unpack('Z23CIII') #do something end This is of course untested because i don't have such a file, but i hope the idea is clear. cheers Simon