Search code examples
rubyieee-754packunpack

Ruby convert 64 bit IEEE 754 hexadecimal to double


I need to output a hex data stream from an IMU into lat long and height values.

The data comes in as double precision hex strings and I need to output them into decimal values.

I tried several pack and unpack values but in the end wasn't able to find a solution except that of writing my own function.

Is there any way of translating this double precision 64bit hex string:

"4044F33333333333"

into this decimal:

41.900000000000000

Using pack and unpack functions?

Are there any libraries able to deal with IEEE 754 numbers?


Solution

  • ["4044F33333333333"].pack('H16').unpack('G').first
    => 41.9
    
    # broken down to steps, showing reversability
    ["4044F33333333333"].pack('H16')
    => "@D\xF333333"
    "@D\xF333333".unpack('G')
    => [41.9]
    [41.9].pack('G')
    => "@D\xF333333"
    "@D\xF333333".unpack('H16')
    => ["4044f33333333333"]