Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 545
Z. Nahman Avatar asked May 14 '26 21:05

Z. Nahman


1 Answers

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

b = '0011111111110000000000000000000000000000000000000000000000000000'

[b].pack('B*').unpack1('G')
#=> 1.0
like image 102
Stefan Avatar answered May 16 '26 22:05

Stefan