[Haskell-cafe] Re: Just for a laugh...

Donald Bruce Stewart dons at cse.unsw.edu.au
Sun Jun 3 21:57:32 EDT 2007


almeidaraf:
> On 6/3/07, Rafael Almeida <almeidaraf at gmail.com> wrote:
> >The site seems to be asking for the internal floating point
> >representation.  So it doesn't matter if it's IEEE 754, if the ints are
> >2-complements, or whatever. I used this code as a quick hack for one of
> >my programs, but I think it would work in this case. It should work for
> >any Storable type.
> >
> >import qualified Data.ByteString as BS
> >import Data.ByteString.Base
> >import Foreign.ForeignPtr
> >import Foreign.Storable
> >binPut num =
> >    do
> >        fptr <- mallocForeignPtrBytes (sizeOf num)
> >        withForeignPtr (castForeignPtr fptr) (\x -> poke x num)
> >        BS.writeFile "/tmp/foo" (BS.reverse $ fromForeignPtr fptr (sizeOf 
> >        num))
> >
> Ops, that reverse was needed for what I was doing, but not needed for
> this particular problem, so the code should actually be:
> 
> import qualified Data.ByteString as BS
> import Data.ByteString.Base
> import Foreign.ForeignPtr
> import Foreign.Storable
> binPut num =
>    do
>        fptr <- mallocForeignPtrBytes (sizeOf num)
>        withForeignPtr (castForeignPtr fptr) (\x -> poke x num)
>        BS.writeFile "/tmp/foo" (fromForeignPtr fptr (sizeOf num))
         ^^^
Interesting use of ByteStrings to print foreigin ptr arrays there. 

-- Don


More information about the Haskell-Cafe mailing list