Saturday, March 19, 2011, 9:10:25 PM, you wrote:

JB> 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?

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

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

JB>   puts the_int
JB> end

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

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

JB> -Jeremy

May the gods bless you, Jeremy.   Exactly the answer I was looking for.