RE: Straightforward conversion from Int <-> Word

-----Original Message----- From: Jan-Willem Maessen [mailto:jmaessen@alum.mit.edu] Sent: 25 February 2002 16:46 To: glasgow-haskell-users@haskell.org Subject: Straightforward conversion from Int <-> Word
I've cast about a bit and haven't been able to find the appropriate functionality, so I'm asking here.
I'd like to convert Int32 to and from Word32 in the good old-fashioned bitwise fashion (perserving modular arithmetic). I have the following code to show what I mean:
intToNat i | i >= 0 = fromIntegral i | otherwise = fromIntegral (i - minBound) + negBound where negBound = fromInteger . negate . toInteger $ (minBound :: Int)
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 correctly for the portions of the numeric range which overlap.
How do I do the straightforward conversion module 2^32? I'm sure it's buried in there somewhere... I can't even turn up an appropriate type signature, though.
But fromIntegral *does* do the right thing, doesn't it?
Numeric.showHex (fromIntegral (-1 :: Int32) :: Word32) "" "0xffffffff"
it does it by a kind of roundabout route, but this is the defined behaviour (at least in GHC). And if you turn optimisation on, the fromIntegral should reduce to a simple cast. Cheers, Simon
participants (1)
-
Simon Marlow