3

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!

2
  • 1
    Presumably binaryString is a string, so you need quotation marks on the right. (As written, binaryString is an integer whose digits are all zeros and ones, and whose two leading zeroes are of no significance) If it is meant to be a string, why not use it's integer value, binaryString.to_i(2) # => 4607182418800017408? You need to edit the question to correct or clarify. Commented Jun 21, 2018 at 16:34
  • Thanks for the reply and suggestion. I added quotes to show that binaryString is, in fact, a string. I am not using the integer value because I know that binaryString correctly represents a double value of 1.0 per the online converter. I'm trying to get ruby to covert to the correct value. I want some way to have ruby yield 1.0 from the binaryString given. Commented Jun 21, 2018 at 16:43

1 Answer 1

3

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

b = '0011111111110000000000000000000000000000000000000000000000000000'

[b].pack('B*').unpack1('G')
#=> 1.0
Sign up to request clarification or add additional context in comments.

1 Comment

Works like a charm. Thank you for your help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.