Iavor S. Diatchki diatchki at
Wed Dec 15 13:21:25 EST 2004

I have been mucking around with bits and hardware recently,
and found the following two functions quite useful.
Perhpas we should add them (or something similar) to Data.Bits?

-- Manipulating bit arrays
-- Warning: this actually uses lazyness :-)

-- | Get an element from a bit vector.
-- 0: least significant element (right-most in math notation)
array .!. index         = let x = fromIntegral (array `shiftR` (bitSize 
x * index))
                          in x

-- | Join two sequences of bits together.
-- Here we use 'fromIntegral' to simply resize bit-vectors.
-- If it does something fancier, the amout we 'shiftL' may be wrong.
-- As long as one sticks to the "usual" types this is not a problem.
b1 `nextTo` b2          = (fromIntegral b1 `shiftL` bitSize b2) .|. 
fromIntegral b2

 > showBin ((-1::Word16) `nextTo` (10::Word8) :: Word32)

 > showBin (((-1::Word16) `nextTo` (10::Word8) :: Word32) .!. 0 :: Word16)

 > showBin (((-1::Word16) `nextTo` (10::Word8) :: Word32) .!. 1 :: Word8)

Usually I don't need to specify nearly as many type annotations simply 
it is obvious from the context what size quantities are needed.


More information about the Libraries mailing list