jfcalvo
jfcalvo

Reputation: 475

How to convert a float number to a binary string and vice versa with Ruby?

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!

Upvotes: 1

Views: 1906

Answers (2)

d11wtq
d11wtq

Reputation: 35298

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).

["0" * 32].pack("b*")                        # => "\x00"
["0" * 32].pack("b*").unpack("F")            # => "\x00".unpack("F") => 0.0
["11".rjust(32, "0")].pack("b*").unpack("F") # => -2.0

I'm not much of an expert in this stuff, however.

Upvotes: 3

Gregory Mostizky
Gregory Mostizky

Reputation: 7261

"0" is actually ASCII 48 so your string is actually an array of 48s.

What you probably wanted to do:

binary_string_number = "\0" * 32

That way you will get an array of zeros which when unpacked will convert to 0.0

Upvotes: 1

Related Questions