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

Tomasz Zielonka tomasz.zielonka at gmail.com
Thu May 31 17:36:54 EDT 2007


On Thu, May 31, 2007 at 08:47:28PM +0100, Andrew Coppin wrote:
> If you're bored... can you come up with a solution to this?
> 
> http://warp.povusers.org/ProgrammingChallenge.html
> 
> (Obviously a pretty silly challenge, but hey.)
> 
> My first instinct was to use Data.Bits - but I see no instance for 
> Double.

You can imitate the C++ code using the FFI libraries:

    import Foreign.Storable
    import Foreign
    import Data.Word
    import Data.Bits

    getDoubleBits :: Double -> IO String
    getDoubleBits d = alloca $ \ptr -> do
        poke ptr d
        bs <- peekArray (sizeOf d) (castPtr ptr :: Ptr Word8)
        return . concatMap (concatMap (show . fromEnum) . flip map [7,6..0] . testBit) $ bs

(I'm not sure this code prints bits in the right order).
You can generalize this to
    getStorableBits :: Storable a => a -> IO String

Best regards
Tomek


More information about the Haskell-Cafe mailing list