如何将64位二进制字符串转换为ruby中的double float?

时间:2022-10-23 21:43:32

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:

我想知道如何将64位二进制字符串转换为ruby中的double float。我的字符串如下:

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.

使用在线转换器(http://www.binaryconvert.com/convert_double.html?)我知道该值应为1.0。但是,我正在尝试使用ruby unpack转换为double,并且我没有得到正确的结果。

double_value = binaryString.unpack("G")

Gives me double_value = 1.3983819593719592e-76

给我double_value = 1.3983819593719592e-76

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

我尝试了其他指令,如“F”和“D”,但没有一个产生正确的结果。

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

我有什么想法我做错了吗?感谢您的帮助!

1 个解决方案

#1


2  

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

unpack期望二进制数据,所以你必须首先使用B打包你的位串:

b = '0011111111110000000000000000000000000000000000000000000000000000'

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

#1


2  

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

unpack期望二进制数据,所以你必须首先使用B打包你的位串:

b = '0011111111110000000000000000000000000000000000000000000000000000'

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