Machine bit representations

Ken Shan ken@digitas.harvard.edu
Wed, 25 Jul 2001 00:25:27 -0400


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

On 2001-07-24T16:51:54-0700, pachinko@magicaldesk.com wrote:
> Hello,
>=20
> Is it possible in Haskell to access the underlying machine bit
> representation of a Float or Double value?
>=20
> 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).
>=20
> 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.
>=20
> 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?

--=20
Edit this signature at http://www.digitas.harvard.edu/cgi-bin/ken/sig
=AB ne g=E2che pas ta vie pour leur id=E9e de patrie =BB le bouton me dit

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

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iD8DBQE7Xko2zjAc4f+uuBURAs04AJoCkbOLGPQeZ06FvhaptJsvHCdRnQCgjdWN
5X6W2l9rzQkN/ZxfeDHwj4M=
=eg/J
-----END PGP SIGNATURE-----

--huq684BweRXVnRxX--