# Hex to float conversion

**URL:** <https://rubytalk.org/t/hex-to-float-conversion/10312>\
**Category:** ruby-talk\
**Created:** [25 February 2004 15:09 UTC](https://rubytalk.org/t/hex-to-float-conversion/10312 "2004-02-25T15:09:49Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Paul\_Rogers](https://avatars.discourse-cdn.com/v4/letter/p/aeb1de/32.png) [@Paul\_Rogers](https://rubytalk.org/u/Paul_Rogers)\
**Post date:** [25 February 2004 15:09 UTC](https://rubytalk.org/t/hex-to-float-conversion/10312/1 "2004-02-25T15:09:49Z")

</div>

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](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?

---

<div class="post-metadata">

**Author:** ![Mark\_J\_Reed1](https://avatars.discourse-cdn.com/v4/letter/m/8491ac/32.png) [@Mark\_J\_Reed1](https://rubytalk.org/u/Mark_J_Reed1)\
**Post date:** [25 February 2004 15:24 UTC](https://rubytalk.org/t/hex-to-float-conversion/10312/2 "2004-02-25T15:24:54Z")

</div>

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](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

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

---

<div class="post-metadata">

**Author:** ![Dave\_Mail\_Archive](https://avatars.discourse-cdn.com/v4/letter/d/f04885/32.png) [@Dave\_Mail\_Archive](https://rubytalk.org/u/Dave_Mail_Archive)\
**Post date:** [25 February 2004 15:28 UTC](https://rubytalk.org/t/hex-to-float-conversion/10312/3 "2004-02-25T15:28:16Z")

</div>

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
