Memory reinterpretation casts for Float/Double and Word32/Word64 in Haskell.
Takes the bit representation of a number and uses it for a different numeric type.
reinterpret_cast from C++ and
float f = 1.23; int i = * (int *) &f; from C.
We offer you fast casts for:
floatToWord :: Float -> Word32 wordToFloat :: Word32 -> Float doubleToWord :: Double -> Word64 wordToDouble :: Word64 -> Double
If you need something like
Int32 or similar,
fromIntegral will do the job
within the integral types (so to/from
Word* are the only conversions needed).
cabal install reinterpret-cast
The way implemented in this package is the fastest possible way known as of now. In particular, it is faster than what
data-binary-ieee754 does at the moment.
For a discussion, see this StackOverflow question.
Benchmark results for
bench/Bench.hs are available here.
In theory, these should all be no-ops, but you must not use
unsafeCoerce or even
unsafeCoerce# for this.
The real solution will be this GHC feature request - please support it.
- Compare to the performance of an
unsafepure FFI call that does
float f = 1.23; int i = * (int *) &f;inside.