Hello, How do I convert a ruby float/double to high endian order hex with high bytes and low bytes.
EXAMPLE:
start with 99.0
end up with
40 58 C0 00 00 00 00 00
high bytes low bytes
Hello, How do I convert a ruby float/double to high endian order hex with high bytes and low bytes.
EXAMPLE:
start with 99.0
end up with
40 58 C0 00 00 00 00 00
high bytes low bytes
The array class has a pack 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 unpack method:
s.unpack("d")
=>[99.0]
Well, like Patrick said, it doesn't take a lot to convert past 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 whether you want to unpack it with the high-order byte in the zero index or the low order byte in the zero index:
E | Double-precision float, little-endian byte order
G | Double-precision float, network (big-endian) byte order