[Haskell-beginners] Extract and integer from a ByteString
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 =
> 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
> 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.
Then you can write:
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.
More information about the Beginners