packBits.hs

Haskell

Public Domain

Pack & unpack bits into bytes in ascending or descending order

Download (right click, save as, rename as appropriate)

Embed

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
import Word (Word8)
import Data.Bits (testBit)

packBitsAsc, packBitsDesc :: [Bool] -> [Word8]

packBitsAsc [] = []
packBitsAsc b = fromIntegral byte : packBitsAsc (drop 8 b)
 where bits = take 8 $ take 8 b ++ repeat False
       byte = foldr (\tf a -> a*2 + fromEnum tf) 0 bits

packBitsDesc [] = []
packBitsDesc b = fromIntegral byte : packBitsAsc (drop 8 b)
 where bits = take 8 $ take 8 b ++ repeat False
       byte = foldl (\a tf -> a*2 + fromEnum tf) 0 bits

unpackBitsAsc, unpackBitsDesc :: [Word8] -> [Bool]
unpackBitsAsc bits = [testBit b i | b <- bits, i <- [0..7]]
unpackBitsDesc bits = [testBit b i | b <- bits, i <- [7, 6 .. 0]]