[Haskell-beginners] Re: Convert bits to bytes

Ertugrul Soeylemez es at ertes.de
Mon Sep 6 23:41:28 EDT 2010


Alec Benzer <alecbenzer at gmail.com> wrote:

> What's the quickest/the best/a way of converting a series of bits into
> bytes? Ie, converting a [Bool] to a [Word8]. So if I had replicate 8 True ++
> replicate 8 False :: [Bool], it would spit out [255,0] :: [Word8].

Here is my variant:

  import Data.Bits

  chunks :: Int -> [a] -> [[a]]
  chunks n = takeWhile (not . null) . map (take n) . iterate (drop n)

  boolToDigit :: Num i => Bool -> i
  boolToDigit False = 0
  boolToDigit True  = 1

  bitsToByte :: Num i => [Bool] -> i
  bitsToByte = sum . zipWith (*) (iterate (*2) 1) . map boolToDigit

  bitsToBytes :: Bits i => [Bool] -> [i]
  bitsToBytes x = y
    where ~y@(y0:ys) = map bitsToByte . chunks (bitSize y0) $ x

It works for every binary type with a fixed length, so you can use it
with Word8, Word16, etc.


Greets,
Ertugrul


-- 
nightmare = unsafePerformIO (getWrongWife >>= sex)
http://ertes.de/




More information about the Beginners mailing list