Straightforward conversion from Int <-> Word

Simon Marlow simonmar@microsoft.com
Tue, 26 Feb 2002 09:58:17 -0000


If intToNat is a blunt instrument, then fromIntegral is the rapier :-)  =
Remember Word is GHC-specific; the FFI doesn't define it.

Simon

> -----Original Message-----
> From: Julian Seward (Intl Vendor) [mailto:v-julsew@microsoft.com]=20
> Sent: 25 February 2002 16:57
> To: jmaessen@alum.mit.edu; glasgow-haskell-users@haskell.org
> Subject: RE: Straightforward conversion from Int <-> Word
>=20
>=20
>=20
> I've found this annoying in the past, and have resorted to hitting
> it on the head (GHC-specifically) with a blunt instrument:
>=20
>    intToNat :: Int -> Word
>    intToNat (I# i#) =3D W# (unsafeCast# i#)
>=20
> This probably defeats the good intentions of the FFI designers,
> but it kinda seems like it'll work on all reasonable architectures.
>=20
> J
>=20
> | -----Original Message-----
> | From: Jan-Willem Maessen [mailto:jmaessen@alum.mit.edu]=20
> | Sent: Monday, February 25, 2002 4:46 PM
> | To: glasgow-haskell-users@haskell.org
> | Subject: Straightforward conversion from Int <-> Word
> |=20
> |=20
> | I've cast about a bit and haven't been able to find the appropriate
> | functionality, so I'm asking here.
> |=20
> | I'd like to convert Int32 to and from Word32 in the good=20
> old-fashioned
> | bitwise fashion (perserving modular arithmetic).  I have=20
> the following
> | code to show what I mean:
> |=20
> |   intToNat i
> |     | i >=3D 0    =3D fromIntegral i
> |     | otherwise =3D fromIntegral (i - minBound) + negBound
> |     where negBound =3D fromInteger . negate . toInteger $=20
> | (minBound :: Int)
> |=20
> | One might think that "intToWord32" and "word32ToInt" in lang/Word
> | would do what I want---but no!  These are depracated, and I must use
> | fromIntegral, which will only perform the conversion=20
> correctly for the
> | portions of the numeric range which overlap.
> |=20
> | How do I do the straightforward conversion module 2^32? =20
> I'm sure it's
> | buried in there somewhere...  I can't even turn up an=20
> appropriate type
> | signature, though.
> |=20
> | -Jan-Willem Maessen
> |=20
> | _______________________________________________
> | Glasgow-haskell-users mailing list
> | Glasgow-haskell-users@haskell.org
> | http://www.haskell.org/mailman/listinfo/glasgow-haskell-users
> |=20
> _______________________________________________
> Glasgow-haskell-users mailing list
> Glasgow-haskell-users@haskell.org
> http://www.haskell.org/mailman/listinfo/glasgow-haskell-users
>=20