On Tue, 18 Jul 2006, Fabio Vitale wrote: > Daniel Martin wrote: >> Fabio Vitale <fabio / sferaconsulting.it> writes: >> >>> I've the need to parse a binary file with the following structure: >>> How can I accomplish this in Ruby? >> >> In addition to parsing this yourself using ruby's String#unpack >> method, you should also look at the BitStruct extension available at >> http://redshift.sourceforge.net/bit-struct/ > > I've found bit-struct very intresting, anyway I cannot figure how to > load a binary file in a newly created bit-structure. > Any help appreciated. > > Say I've an imap.mrk binary file, > I've defined class MRK as follows: > > 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: harp:~ > cat a.rb require 'bit-struct' class C < BitStruct unsigned :a, 16 unsigned :b, 16 unsigned :c, 16 end c = C.new 'a' => 42 p c buf = c.to_s p buf c = C.new buf p c.a harp:~ > ruby a.rb #<C a=42, b=0, c=0> "\000*\000\000\000\000" 42 incidentally, you are probably going to want class MRK < BitStruct unsigned :version, 32, "Version" unsigned :uid_Validity, 32, "UIDValidity" unsigned :uid_next, 32, "UIDNext" unsigned :last_write_counter, 32, "LastWriteCounter" rest :unused, "Unused" end the field size declares the number of __bits__ not __bytes__. http://redshift.sourceforge.net/bit-struct/doc/index.html regards. -a -- suffering increases your inner strength. also, the wishing for suffering makes the suffering disappear. - h.h. the 14th dali lama