I want to convert Float to a list of bytes [Word8] (and vice versa). I see there is a Storable class which could maybe be used for this, but I'd like to avoid using IO monad as this has nothing to do with IO.
What is it that you want? If you want to convert between the Float and its actual bit representation, you can use data-binary-ieee754 (uses Foreign.Storable and unsafePerformIO under the hood) or cereal-ieee754. The latter doesn't use Storable or IO, it writes the value to an STUArray, casts the array and reads a value of the other type. Both packages give you a conversion Float <-> Word32 (or Double <-> Word64), converting the WordN to [Word8] is easy.
I recommend the Data.Binary library.
See here:
Prelude Data.Binary> encode (13.7 :: Double)
Chunk "\SOH\SOH\NUL\NUL\NUL\NUL\NUL\NUL\NUL\affffff\ESC\255\255\255\255\255\255\255\207" Empty
Prelude Data.Binary Data.ByteString.Lazy> Data.ByteString.Lazy.unpack $ encode (13.7 :: Double)
[1,1,0,0,0,0,0,0,0,7,102,102,102,102,102,102,27,255,255,255,255,255,255,255,207]
If you're wondering why the representation is that big, it's because of the implementation of the Binary instance for Float and Double uses decodeFloat function:
decodeFloat :: RealFloat a => a -> (Integer, Int)
This is done to keep the implementation as generic as the Haskell Report (which doesn't specify IEEE754 or anything like that).
To get the actual binary representation of a Float, you need to use Storable AFAIK.
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