Wednesday, January 2, 2008

Reading binary files with haskell, simple snippet

There is a hackage haskell package that is external from the core haskell libraries that includes support for reading writing binary files and support big/little endian encoding and decoding. I used this, in order to manipulate the botlist binary database format. It wasn't intuitive as I didn't quite get the understand the Binary.GET monad which contained the getWord16le, getWord16be functions and how it related to the pure Binary monad, but after a while it made it sense.

Download and review this haskell source to see what I ended up with. I defined a DatabaseFile type which includes two magic number words (unsigned shorts of 16 bits each) and then populated the fields from the binary file.

instance Binary SpiderDatabase where
put _ = do BinaryPut.putWord16le 0
get = do
magicnumbera <- BinaryGet.getWord16be
magicnumberb <- BinaryGet.getWord16be
return (SpiderDatabase {magicNumberA=magicnumbera,

No comments: