2

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.

1 Answer 1

5

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.