[Haskell-beginners] Lost in binary input

Alexey Khudyakov alexey.skladnoy at gmail.com
Sat Nov 8 05:55:09 EST 2008


On Saturday 08 November 2008 12:38:46 Moritz Tacke wrote:
> Hi!
>
> I'm desperately trying to read a binary file into a list of Word16s.
> After heavily borrowing from the
> http://www.haskell.org/haskellwiki/DealingWithBinaryData - tutorial
> (which accounts for the only few working lines of my code), I am still
> left totally lost.
> What I need is a piece of code that reads these Word16s and gives them
> to me in a way that I can apply usual functions on it - should be
> easy, was my first thought some hours ago...
>


You should use runGet to escape from Get monad. For example:

> import qualified Data.ByteString.Lazy as ByteString
> import Data.Binary.Get
> import Data.Word
>
> readAsWords::Get [Word16] 
> readAsWords = do
>   empty <- isEmpty
>   if empty
>     then return []
>     else do v <- getWord16be
>             rest <- readAsWords
>             return (v : rest)
> 
> main = do
>   binary_data <- ByteString.readFile "your_file"
>   let
>       words :: [Word16]
>       words = runGet readAsWords binary_data
>       -- Now you can do whatever you want 
>   return ()



More information about the Beginners mailing list