I would like to know the best way to convert a float number to binary string and vice versa a binary string to float number.
I’m working with genetics algorithms and I need to save the binary representation of a float number in the range [0-1], so additionally I need to know the number of bits that Ruby uses to save a float number in memory.
I’m trying to solve this problem with String#Unpack method but I get a strange result:
binary_string_number = "0" * 32
=> "00000000000000000000000000000000"
binary_string_number.unpack("F")
=> [6.409690556097303e-10]
The result should be 0.0 right?, I don’t understand this behavior.
Thank you!
I think you need to pack your String before you try to unpack it to a Float. What you’ve got is basically a String representing a series of bits, but not the actual bits you’re trying to read (if I’m understanding your question correctly).
I’m not much of an expert in this stuff, however.