From: Michael Neumann Date: 2001-10-23T22:27:49+09:00 Subject: [ruby-talk:23048] Re: Howto read binary data? Martin Kahlert wrote: > Hi! > I want to read a file containing double values in binary representation, > i.e. they have been written from C using > > double variable; > write(fd, &variable, sizeof(variable)); For this purpose, I wrote some time ago a class BinaryReader: class BinaryReader DEF = [ [ :short, 2, 's' ], [ :ushort, 2, 'S' ], [ :int, 4, 'i' ], [ :uint, 4, 'I' ], [ :float, 4, 'f' ], [ :double, 8, 'd' ] ] DEF.each do |meth, size, format| eval %{ def read_#{ meth }(n = 1) _read(n, #{size}, '#{ format }') end } end def initialize( handle ) @handle = handle end private def _read(n, size, format) bytes = n * size str = @handle.read(bytes) raise "failure during read" if str.nil? or str.size != bytes val = str.unpack(format * n) if n == 1 val.first else val end end end You can use this as follows: file = File.new(...) file.binary # only neccessary on Windows reader = BinaryReader.new( file ) aFloat = reader.read_float int1, int2 = reader.read_int(2) # read two integers # ... read_double, read_ushort etc.. Regards, Michael > How can i read this file from ruby and stuff the data into a ruby double > variable? (The file has been built on the same machine, so endianess should > not be a problem). See Array#pack and String#unpack. Regards, Michael -- Michael Neumann merlin.zwo InfoDesign GmbH http://www.merlin-zwo.de