How to convert double to hex?

How to convert ruby ​​float / double to high endian hex with high bytes and lower bytes.

Example:

start with 99.0

finish with

40 58 C0 00   00 00 00 00
high bytes    low bytes
+5
source share
2 answers

Well, as Patrick said , converting the past is not required using Array\#pack.

irb> [99.0].pack('G').split('').map { |ds| ds[0] }
#=> [64, 88, 192, 0, 0, 0, 0, 0]
irb> _.map { |d| "%02x" % d }
#=> ["40", "58", "c0", "00", "00", "00", "00", "00"]
irb> [99.0].pack('E').split('').map { |ds| ds[0] }
#=> [0, 0, 0, 0, 0, 192, 88, 64]
irb> _.map { |d| "%02x" % d }    
#=> ["00", "00", "00", "00", "00", "c0", "58", "40"]

So, it depends on whether you want to unpack it using the high byte at the zero index or the low byte at the zero index:

      E     |  Double-precision float, little-endian byte order
      G     |  Double-precision float, network (big-endian) byte order
+6
source

The array class has a batch method:

a = [99.0]
s = a.pack("d")
s
=> "\000\000\000\000\000\300X@"

This gives you a byte string, but converting from that to hex for printing should be trivial.

If you want to go the other way, the string class has an unpacking method:

s.unpack("d")
=>[99.0]
0

All Articles