Search code examples
haskellbytestring

Haskell Bytestring to Float Array


Hi have binaries of float data (single-precision 32-bit IEEE) that I would like to work on. How can I best load this for further use, ideally as (IOArray Int Float).

bytesToFloats :: ByteString -> [Float]
bytesToFloatArray :: ByteString -> IOArray Int Float

Solution

  • If you've got bog standard single-precision floats, and you just want to work them over in Haskell, you can always be down and dirty about it:

    import Data.ByteString.Internal as BS
    import qualified Data.Vector.Storable as V
    
    bytesToFloats :: BS.ByteString -> V.Vector Float
    bytesToFloats = V.unsafeCast . aux . BS.toForeignPtr
      where aux (fp,offset,len) = V.unsafeFromForeignPtr fp offset len