4

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
Fabian Barkhau
  • 1,349
  • 2
  • 12
  • 31

4 Answers4

2

I think you might be happier with Data.Vector:

http://www.haskell.org/haskellwiki/Numeric_Haskell:_A_Vector_Tutorial#Parsing_Binary_Data

misterbee
  • 5,142
  • 3
  • 25
  • 34
2

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
Anthony
  • 3,771
  • 23
  • 16
2

You could also use cereal library, for example:

import Control.Applicative
import Data.ByteString
import Data.Serialize

floatsToBytes :: [Float] -> ByteString
floatsToBytes = runPut . mapM_ putFloat32le

-- | Parses the input and returns either the result or an error description.
bytesToFloat :: ByteString -> Either String [Float]
bytesToFloat = runGet $ many getFloat32le
Petr
  • 62,528
  • 13
  • 153
  • 317
1

If you can convert 4 bytes to a Word32, you can use the function wordToFloat in the data-binary-ieee754 package to convert it to a float. You could then load this into any kind of list-like structure you want to manipulate it.

bheklilr
  • 53,530
  • 6
  • 107
  • 163