Pergunta

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
Foi útil?

Solução

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

Outras dicas

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

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top