From: Logan Capaldo Date: 2006-06-12T04:26:03+09:00 Subject: Re: Converting a Float back to bytes On Jun 9, 2006, at 5:44 PM, Harris Reynolds wrote: > This is good stuff. I am now getting the correct Float object > (21.0) from a string of bytes ("@5\000\000\000\000\000\000"). > Now... here is a question... is there an easy way to go from the > Float back to bytes. This seems like it may be much more difficult. > > something like this... > > float_object = 21.0 > bytes = SOME_API_HERE.convert(float_object) > > I think a result of this work I am doing should be a general > purpose BitConverter class similar to what .Net offers. This would > make working with binary data in Ruby much less painful. > > thanks for any help, > > ~harris > > p.s. Mike... thanks a bunch for the help on going from Bytes to a > Float!!! I owe you... are you going to be at RailsConf? > > > > ----- Original Message ---- > From: Mike Stok > To: ruby-talk ML > Sent: Thursday, June 8, 2006 10:49:36 PM > Subject: Re: Converting 8 bytes to a Float > > > On 8-Jun-06, at 10:39 PM, Harris Reynolds wrote: > >> Mike... thanks for the tip. My mileage is varying though... here >> is the same irb session on my machine: >> >> irb(main):004:0> s = "" >> => "" >> irb(main):005:0> s << 64 << 53 << "\0" * 6 >> => "@5\000\000\000\000\000\000" >> irb(main):006:0> s.unpack('D') >> => [6.73510288410787e-320] >> >> I'm not getting the clean result for some reason. >> > > I'm on a PowerPC, and you're probably on an x86. Our endian-ness is > different. > > D uses native format to unpack the bytes, if your bytes are laid out > the way you said they are then you probably want to use G which is > specifically "big endian". > > See http://en.wikipedia.org/wiki/Endian for more background. > > Hope this helps, > > Mike > > -- > Mike Stok > http://www.stok.ca/~mike/ > > The "`Stok' disclaimers" apply. [21.0].pack("D") no?