[Haskell-cafe] Writing binary files

Udo Stenzel u.stenzel at web.de
Mon Aug 21 09:17:58 EDT 2006


Neil Mitchell wrote:
> I'm trying to write out a binary file, in particular I want the
> following functions:
> 
> hPutInt :: Handle -> Int -> IO ()
> 
> hGetInt :: Handle -> IO Int
> 
> For the purposes of these functions, Int = 32 bits, and its got to
> roundtrip - Put then Get must be the same.
> 
> How would I do this? I see Ptr, Storable and other things, but nothing
> which seems directly useable for me.


hPutInt h = hPutStr h . map chr . map (0xff .&.)
                      . take 4 . iterate (`shiftR` 8)
		    
hGetInt h = replicateM 4 (hGetChar h) >>=
            return . foldr (\i d -> i `shiftL` 8 .|. ord d) 0

This of course assumes that a Char is read/written as a single low-order
byte without any conversion.  But you'd have to assume a lot more if you
started messing with pointers.  (Strange, somehow I get the feeling, the
above is way too easy to be the answer you wanted.)


Udo.
-- 
Worrying is like rocking in a rocking chair -- It gives
you something to do, but it doesn't get you anywhere.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 189 bytes
Desc: Digital signature
Url : http://www.haskell.org//pipermail/haskell-cafe/attachments/20060821/cf48004c/attachment.bin


More information about the Haskell-Cafe mailing list