# hex to float conversion - Ruby

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?...

1. ## 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 Guest

2. ## Re: hex to float conversion

ca (Paul) writes:

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
Mark Guest

3. ## Re: hex to float conversion

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

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

Dave Guest

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•