Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zero Fill Right Shift in Haskell?

Tags:

haskell

I'm having a little tinker with Haskell (and thouroughly enjoying myself) and I now want to do a zero-fill right shift.

I trotted on over to hackage and found Data.Bits, whipped up ghci and here's what I typed (well, I didn't type the -3 of course):

:m Data.Bits   
shiftR (-9) 2
-3

Fantatstic, a regular right shift, just what I expected.

OK, now I'll actually read the docs. OK, I see unsafeShiftR, but that's not quite what I want.

So, what have I missed? Is there a zero-fill right shift function available to me in Haskell somewhere (i.e. one that returns 1073741821 when -9 is shifted right by 2)?

like image 296
kmp Avatar asked Dec 12 '13 14:12

kmp


1 Answers

Data.Bits takes signed types into account. However, since any zero fill right shift with non-zero shift will result in a unsigned type, you can simply transform your input to a word of the correct size:

-- :m Data.Word
-- shiftR ((fromIntegral x) :: Word32) 2
shiftR (-9 :: Word32) 2
1073741821
like image 143
Zeta Avatar answered Sep 22 '22 09:09

Zeta