On 03/19/2011 09:44 PM, Ralph Shnelvar wrote:
> I have a file I need to read.
> 
> The file has ANSI text interspersed with doubles (64-bit standard floating point numbers).
> 
> Let's say the floating point number is at 9 bytes from the beginning of the file.   How can I read the number and then convert the number to an integer?
> 
> I scoured Dave Thomas' "Programming Ruby 1.9" and the web but could find nothing about this.
> 
> It's gotta be easy, doesn't it?

Assuming you're running with a 64-bit enabled Ruby and the bytes in the
file are in network byte order:

# Open the file for reading with a binary encoding.
File.open('datafile', 'rb') do |f|
  # Seek to the first byte of the floating point data.
  f.seek(8)
  # Read 8 bytes of data to get the 64-bit float.
  the_float_as_string = f.read(8)
  # Convert the string of bytes into a floating point number.
  the_float = the_float_as_string.unpack('G')[0]
  # Convert the floating point number to an integer.
  the_int = the_float.to_i

  puts the_int
end

It's possible that this may still work on a 32-bit Ruby, but I don't
have one to test with right now.  The issue would be the behavior of the
'G' format directive for the unpack method.  It may only handle 32-bit
floats on 32-bit Ruby interpreters.  I'm not sure.

See the documentation for String#unpack for more directives in case your
file uses something other than network byte order to store the floats.

-Jeremy