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
To convert it to double (IEEE754 Double precision 64-bit), you need to use the following code: var hex = "0x4007B425F202107B"; var int64Val = Convert. ToInt64(hex, 16); var doubleVal = BitConverter. Int64BitsToDouble(int64Val);
Take decimal number as dividend. Divide this number by 16 (16 is base of hexadecimal so divisor here). Store the remainder in an array (it will be: 0 to 15 because of divisor 16, replace 10, 11, 12, 13, 14, 15 by A, B, C, D, E, F respectively). Repeat the above two steps until the number is greater than zero.
The std::hexfloat format is intended to dump out the exact repesentation of a floating point value. The string represention isn't for human consumption but primarily to restore the exact same representation again. Thus, it does not make sense to truncate the format in any way based on any stream setting.
Given hexadecimal number is 7CF. To convert this into a decimal number system, multiply each digit with the powers of 16 starting from units place of the number. From this, the rule can be defined for the conversion from hex numbers to decimal numbers.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With