[Haskell-beginners] Extract and integer from a ByteString

Yitzchak Gale gale at sefer.org
Wed Jun 16 05:07:06 EDT 2010


Tom Hobbs wrote:
> I have a stream of bytes...
> Where the first four bytes tell me the number of bytes I should read next in
> order to get some string value...
>
> What I have is code similar to the following;
>
> readFromStream address port     =
>                do
>                h <- connectTo address (PortNumber port)
>                hSetBuffering h NoBuffering
>                L.hPut h (encode (0xFAB10000 :: Word32))
>                p <- L.hGet h 4
>                readData h (extractInt((L.unpack p)))
>
> extractInt      = foldl addDigit 0
>                where
>                addDigit num d = 10*num + d
>
> readData h c    = do
>                print c
>                s <- L.hGet h c
>                print s

You're looking for the binary package. That is a general
library for encoding and decoding of binary data streams
via lazy bytestrings.

http://hackage.haskell.org/package/binary

Then you can write:

import Data.Binary.Get
...
    n <- fmap (runGet word32be) $ L.hGet h 4
    theString <- L.hGet h n

This gives you theString as a lazy bytestring, of course.
You take it from there.

Regards,
Yitz


More information about the Beginners mailing list