Hex to float conversion

I have a hex number that I need to convert to a 32 bit float

eg 0x44361000 => 728.25 (from
http://sandbox.mc.edu/~bennet/cs110/flt/ftod.html)

Ive written some ugly code to do it, but Im sure there must be a nicer
way with pack/unpack/sprintf

I also need to go from floats to Hex too

Can any one help?

paul.rogers@shaw.ca (Paul) writes:

I have a hex number that I need to convert to a 32 bit float

eg 0x44361000 => 728.25 (from
Float to Decimal Conversion)

Ive written some ugly code to do it, but Im sure there must be a nicer
way with pack/unpack/sprintf

If you have the original hex in a string, you’ll need to convert it to
an int first. Then you have to put it in an array, call pack on the array,
and call unpack on the resulting string. What you get out of that is
again an array so you need to extract the element you want. The
whole thing looks like this:

irb(main):001:0> s=‘0x44361000’
=> “0x44361000”
irb(main):002:0> f=[s.to_i(16)].pack(‘L’).unpack(‘F’)[0]
=> 728.25

Going the other way is similar:

irb(main):003:0> sprintf(“0x%08x”, [f].pack(‘F’).unpack(‘L’)[0])
=> “0x44361000”

-Mark

I’m not sure about the various sign-bit issues, but something like:

hex = 0x44361000
p [ hex ].pack(“I”).unpack(“f”)[0]

Might get you started.

Cheers

Dave

···

On Feb 25, 2004, at 9:09, Paul wrote:

0x44361000 => 728.25