Reputation: 257
Can someone tell me how to convert a 32-bit binary string to an IEEE 754 floating point value in Ruby?
For example, the binary string "01000001100101110011001100110011" (0x41973333) should convert to 18.9, but I can't figure out how to do this using Ruby.
I'm trying to get the same values returned by: https://www.h-schmidt.net/FloatConverter/IEEE754.html
Thanks.
Upvotes: 2
Views: 491
Reputation: 54303
That was a fun one!
You need String#unpack and Array#pack :
["01000001100101110011001100110011"].pack('B*').unpack('g').first
#=> 18.899999618530273
[18.9].pack('g').unpack('B*').first
#=> "01000001100101110011001100110011"
'g'
is :
g | Float | single-precision, network (big-endian) byte order
'B*'
is multiple :
B | String | bit string (MSB first)
Upvotes: 5