Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hex Representation of Floats in Haskell

I want to convert a Haskell Float to a String that contains the 32-bit hexadecimal representation of the float in standard IEEE format. I can't seem to find a package that will do this for me. Does anybody know of one?

I've noticed that GHC.Float offers a function to decompose a Float into its signed base and exponent (decodeFloat), but this provides a 14- and 8-digit hex number for the base and exponent, respectively, which takes up much more than 32 bits. This doesn't seem to help.

If there's an easier way to do this that I'm not seeing, please let me know.

like image 926
Jeremy Avatar asked Feb 15 '10 23:02

Jeremy


1 Answers

The float-ieee package is pure Haskell-98, but very CPU intensive. If you are going to need to do this many times, and don't mind being GHC specific, then you use code like this, which extracts the IEEE representation of a Double as a Word64:

import GHC.Prim
import GHC.Types
import GHC.Word

encodeIEEEDouble :: Double -> Word64
encodeIEEEDouble (D# x) = W64# (unsafeCoerce# x)

decodeIEEEDouble :: Word64 -> Double
decodeIEEEDouble (W64# x) = D# (unsafeCoerce# x)

You can code something similar for Float and Word32.

like image 129
MtnViewMark Avatar answered Sep 21 '22 06:09

MtnViewMark