[Haskell-beginners] Bit arithmetic in Haskell

Brent Yorgey byorgey at seas.upenn.edu
Tue Dec 9 08:02:46 EST 2008


On Tue, Dec 09, 2008 at 05:30:28PM +0600, Artyom Shalkhakov wrote:
> Hello,
> 
> I'm trying to do some bit arithmetic. Here's the function:
> 
> > import Data.Bits
> > import Data.Word
> >
> > g :: Word32 -> [Word32]
> > g x = [(x `shiftR` 24) .&. 0xFF,
> >        (x `shiftR` 16) .&. 0xFF,
> >        (x `shiftR` 8) .&. 0xFF,
> >        x .&. 0xFF]
> 
> This function should give bytes for the given number, like this:
> 
> g 255 -> [0,0,0,255]

This is the answer I get when I evaluate (g 255).

> g 256 -> [0,0,1,255]

This is incorrect -- the bytes for 256 are [0,0,1,0], which is
correctly computed by g.  [0,0,1,255] would be 1*256 + 255 = 511, and
giving 511 as input to g indeed results in [0,0,1,255].

> g 65535 -> [0,0,255,255]

When I evaluate (g 65535) this is what I get, too.

In short, it seems to me that g works perfectly.  If it doesn't work
for you, can you give specific examples of the output it should give,
and the output you get instead?

-Brent


More information about the Beginners mailing list