Z. Nahman
Z. Nahman

Reputation: 33

How to convert 64 bit binary string to a double float in ruby?

I am wondering how to convert a 64 bit binary string to a double float in ruby. The string that I have is as follows:

binaryString = "0011111111110000000000000000000000000000000000000000000000000000"

Using an online converter (http://www.binaryconvert.com/convert_double.html?) I know that the value should be 1.0. However, I'm attempting to use the ruby unpack to convert to double, and I'm not getting the correct result.

double_value = binaryString.unpack("G")

Gives me double_value = 1.3983819593719592e-76

I've tried other directives like "F" and "D", but none yield correct results.

Any ideas what I am doing wrong? Thank you for the help!

Upvotes: 3

Views: 408

Answers (1)

Stefan
Stefan

Reputation: 114158

unpack expects binary data, so you have to pack your bit string first using B:

b = '0011111111110000000000000000000000000000000000000000000000000000'

[b].pack('B*').unpack1('G')
#=> 1.0

Upvotes: 3

Related Questions