manusvs650
manusvs650

Reputation: 241

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 try several options of pack and unpack without success.

IEEE : http://en.wikipedia.org/wiki/Single-precision_floating-point_format

Manu

Upvotes: 3

Views: 486

Answers (1)

dbenhur
dbenhur

Reputation: 20408

$ 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"

Upvotes: 4

Related Questions