[Haskell-cafe] Basic binary IO

Don Stewart dons at galois.com
Sun Jan 20 02:34:34 EST 2008


jamie.love:
> Hello all,
> 
> I'm wondering if anyone has a reference to any binary IO and data 
> conversion tutorials.

A good place to start looking is Data.Binary,

    http://hackage.haskell.org/cgi-bin/hackage-scripts/package/binary
  
> I'm playing around with generating a BMP file in haskell, and am a 
> little stuck on the "best" way to go about the simple task of creating 
> the BMP header. The header is
> 
> "BM" + 4 bytes for file size + 4 bytes reserved + 4 bytes for offset 
> where data begins.
> 
> I have the basis starting off at:
> 
> bmpHeader = runPut $
>    [ 0x42, 0x4D ] ++
>    [0 , 0, 0, 0] ++
>    [0 , 0, 0, 0] ++
>    [14 :: Int32]

    bmpHeader = runPut $ do
        put 'B'
        put 'M'
        put (0  :: Int32)
        put (0  :: Int32)
        put (14 :: Int32)

Yields the lazy bytestring,

    "BM\NUL\NUL\NUL\NUL\NUL\NUL\NUL\NUL\NUL\NUL\NUL\SO"

> (where B is Data.ByteString)
> 
> I'm wondering how I can:
> 
> 1/ convert a 32 bit number (Int32, Char32) to 4 Char8 elements

Data.Binary.put (x :: Int32) etc.

> 2/ rotate bits/bytes in a 32 bit Char32 (or Int32) so they are 
> explicitly little-endian (I work on a mac powerbook, and it is big-endian)

Use the little endian 'put' primitives,

    putWord32le (fromIntegral (7 :: Int32))

> 3/ convert an Integer or Int type to an Int32 type
> 
> Any pointers or suggestions would be helpful.

fromIntegral

Data.Binary should support all this nicely, I hope.

-- Don


More information about the Haskell-Cafe mailing list