Forum: Ruby Converting hex floats

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
0d616af377890ddfad05cdee988146a9?d=identicon&s=25 Matt Bauer (mrbauer1)
on 2006-05-04 00:44
What is the easiest way to convert a hex value like:

0x000000000000F03F (big endian, IEEE754)

to a Float in Ruby?

Thanks,
Matt
2ffac40f8a985a2b2749244b8a1c4161?d=identicon&s=25 Mike Stok (Guest)
on 2006-05-04 01:03
(Received via mailing list)
On 3-May-06, at 6:44 PM, Matt Bauer wrote:

> Posted via http://www.ruby-forum.com/.
>
>

Probably using pack and unpack, my first guess is something like

irb(main):001:0> [0x000000000000F03F].pack('Q').unpack('G')
=> [3.03865194161742e-319]


but now I have to look up IEEE and it looks reasonable:

irb(main):002:0> [0x0000000000000000].pack('Q').unpack('G')
=> [0.0]
irb(main):003:0> [0x8000000000000000].pack('Q').unpack('G')
=> [-0.0]

and using a sample single precision number in binary from http://
www.psc.edu/general/software/packages/ieee/ieee.html

0 10000001 10100000000000000000000 = +1 * 2**(129-127) * 1.101 = 6.5

irb(main):005:0> [0b01000000110100000000000000000000].pack('L').unpack
('g')
=> [6.5]

Hope this helps,

Mike

--

Mike Stok <mike@stok.ca>
http://www.stok.ca/~mike/

The "`Stok' disclaimers" apply.
This topic is locked and can not be replied to.