Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert between Float and [Word8]?

Tags:

haskell

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.

like image 818
Karolis Juodelė Avatar asked Dec 22 '11 08:12

Karolis Juodelė


Video Answer


2 Answers

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.

like image 178
Daniel Fischer Avatar answered Oct 14 '22 06:10

Daniel Fischer


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.

like image 5
opqdonut Avatar answered Oct 14 '22 05:10

opqdonut