Search code examples
haskellbitwise-operators

What do I need to import to do bitwise operations?


I'm trying to use bitwise operators and I can't figure out what I need to import.

$ cat tmp.hs
import Data.Word
import Data.Bits

mask = 0xff :: Word64
v = 98213 :: Word64

lsb = mask & v

And this is what I see:

$ ghci tmp.hs 
GHCi, version 9.2.8: https://www.haskell.org/ghc/  :? for help
[1 of 1] Compiling Main             ( tmp.hs, interpreted )

tmp.hs:7:12: error:
    Variable not in scope: (&) :: Word64 -> Word64 -> t
  |
7 | lsb = mask & v
  |            ^
Failed, no modules loaded.
ghci> 

Solution

  • You already imported this. But in Haskell, the bitwise operators are (.&.) :: Bits a => a -> a -> a, (.|.) :: Bits a => a -> a -> a, and (.^.) :: Bits a => a -> a -> a, so:

    lsb = mask .&. v