Machine bit representations

Ken Shan
Wed, 25 Jul 2001 00:25:27 -0400

Content-Type: text/plain; charset=iso-8859-1
Content-Disposition: inline
Content-Transfer-Encoding: quoted-printable

On 2001-07-24T16:51:54-0700, wrote:
> Hello,
> Is it possible in Haskell to access the underlying machine bit
> representation of a Float or Double value?
> I need to be able to be able to send this bit representation as a
> list of bytes in network byte order to a process running on a
> different platform (with a different host byte order to my
> platform).
> For reference, I run Haskell under Linux on Intel. The processes I
> want to communicate with run under Sun Solaris, Hitachi HPUX and
> Java everywhere.
> Any suggestions, for any Haskell translator much appreciated.

If you're using GHC, you should be able to get at the raw bits of the
machine representation using some Storable + Ptr + MarshallAlloc
trickery.  (These are modules in -package lang.)

I tested the following on GHC5 on i386-linux:

    module Cast (cast) where

    import Storable (Storable, sizeOf, peek)
    import MarshalUtils (withObject)
    import IOExts (unsafePerformIO)
    import Ptr (castPtr)

    cast :: (Storable a, Storable b) =3D> a -> b
    cast a =3D b where
      b | sizeOf a =3D=3D sizeOf b =3D
        unsafePerformIO $ withObject a $ peek . castPtr

I was able to get

    (cast :: Int -> Char) 98 =3D=3D 'b'

This might work with other compilers as well, but I don't know...

Fun fun fun!  More efficient implementations?

Edit this signature at
=AB ne g=E2che pas ta vie pour leur id=E9e de patrie =BB le bouton me dit

Content-Type: application/pgp-signature
Content-Disposition: inline

Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see