From: Daniel Martin Date: 2006-07-18T05:48:47+09:00 Subject: Re: How can I parse binary files? Fabio Vitale writes: > And now: how to populate the mrk instance just created from the imap.mrk > binary file? First off, the other message's advice about your field sizes should be taken (you want to use "32", not "4"). Also, you almost certainly want to add :endian => :native to your structure. Finally, you'll want to adjust the bit_length method of your MRKHeader class since it won't construct the appropriate length just from the field info. class MRKHeader < BitStruct unsigned :version, 32, "Version", :endian => :native unsigned :uid_Validity, 32, "UIDValidity", :endian => :native unsigned :uid_next, 32, "UIDNext", :endian => :native unsigned :last_write_counter, 32, "LastWriteCounter", :endian => :native rest :unused, "Unused" def MRKHeader.bit_length super 36*8 end end Okay, now let's assume that you also define the per-message structure using BitStruct as MRKMessage. (For the message code, you don't need to redefine bit_length since it can be computed straight from the fields. Do however use the endianness option on all the integers) Then: File.open("imap.mrk") {|f| head_string = f.read(MRKHeader.round_byte_length) raise "No header!" unless head_string mrk_header = MRKHeader.new(head_string) puts mrk_header.inspect while msg_string = f.read(MRKMessage.round_byte_length) do puts MRKMessage.new(msg_string) end }