Data.Bits
Iavor S. Diatchki
diatchki at cse.ogi.edu
Wed Dec 15 13:21:25 EST 2004
Hello,
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
Examples:
> showBin ((-1::Word16) `nextTo` (10::Word8) :: Word32)
"00000000111111111111111100001010"
> showBin (((-1::Word16) `nextTo` (10::Word8) :: Word32) .!. 0 :: Word16)
"1111111100001010"
> showBin (((-1::Word16) `nextTo` (10::Word8) :: Word32) .!. 1 :: Word8)
"11111111"
Usually I don't need to specify nearly as many type annotations simply
because
it is obvious from the context what size quantities are needed.
-Iavor
More information about the Libraries
mailing list