How to convert binary32 to float in ruby
I have a binary32 encoded in IEEE 32.
How to convert 0x0040EDC2 to -118.625?
I have tried multiple package and unpack options with no success.
IEEE: http://en.wikipedia.org/wiki/Single-precision_floating-point_format
Mana
+3
source to share
1 answer
$ irb
irb(main):001:0> bin = "\x00\x40\xED\xC2"
=> "\000@\355\302"
irb(main):002:0> bin.unpack 'f'
=> [-118.625]
irb(main):003:0> bin.unpack 'e'
=> [-118.625]
irb(main):004:0> bin.unpack 'F'
=> [-118.625]
irb(main):005:0> i = 0x0040edc2
=> 4255170
irb(main):006:0> bin = [i].pack('L')
=> "\xC2\xED@\x00"
irb(main):007:0> bin.unpack 'g'
=> [-118.625]
irb(main):008:0> RUBY_PLATFORM
=> "x86_64-linux"
irb(main):009:0> RUBY_VERSION
=> "1.9.2"
+4
source to share