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

Rafael Almeida almeidaraf at gmail.com
Sun Jun 3 21:45:00 EDT 2007


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))


More information about the Haskell-Cafe mailing list