Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a double to hex?

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
like image 447
Allyn Avatar asked Apr 08 '09 00:04

Allyn


People also ask

How do you convert hexadecimal to double?

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);

How do you convert a floating number to hexadecimal?

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.

What is Hexfloat?

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.

How do you convert hexadecimal to decimal?

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.


1 Answers

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
like image 193
rampion Avatar answered Sep 29 '22 05:09

rampion