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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With