Thanks - I thought there would be some api for it but I see it's pretty simple to do on your own.<div><br></div><div>I came up with this (dealing with non-multiple of 8 numbers of bits)</div><div><br></div><div><div><div>
<div>bitsToBytes :: [Bool] -> [Word8]</div><div>bitsToBytes [] = []</div><div>bitsToBytes bits = map bitsToByte (getChunks bits)</div><div> where bitsToByte = foldl' (\byte bit -> byte*2 + if bit then 1 else 0) 0</div>
<div><br></div><div>getChunks :: [Bool] -> [[Bool]]</div><div>getChunks [] = []</div><div>getChunks xs</div><div> | length xs < 8 = getChunks $ take 8 (xs ++ repeat False)</div><div> | otherwise =</div><div> let (these,rest) = splitAt 8 xs</div>
<div> in these:getChunks rest</div></div><div><br></div></div><br><div class="gmail_quote">On Thu, Sep 2, 2010 at 3:18 AM, David Virebayre <span dir="ltr"><<a href="mailto:dav.vire%2Bhaskell@gmail.com">dav.vire+haskell@gmail.com</a>></span> wrote:<br>
<blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex;">I could have been a bit more verbose.<br>
<br>
The way I see it, since you have an arbitrary long list of 'bits' that<br>
you want to convert into bytes, the first thing to do is to group this<br>
list into sublists of 8 bits.<br>
<br>
That's what chunk does: it splits the list at the 8th element, and<br>
recursively does it for the rest of the list, until the list is empty.<br>
<br>
One problem with that is that if the length of the list isn't a<br>
multiple of 8, then the last byte might be incorrect.<br>
<div class="im"><br>
> chunk :: [Bool] -> [[ Bool ]]<br>
> chunk [] = []<br>
> chunk l = a : chunk b<br>
> where (a,b) = splitAt 8 l<br>
<br>
</div>This one converts a list of 'bits' into a number. The head of the list<br>
is assumed to be the most significant bit :<br>
<div class="im"><br>
> conv1 = foldl' (\a b -> a*2 + if b then 1 else 0) 0<br>
<br>
</div>if we want the head of the list to be the least significant bit, then<br>
you can convert with foldr :<br>
<br>
> conv1' = foldr (\b a -> a*2 + if b then 1 else 0) 0<br>
<br>
Now converting the whole list is just a matter converting the whole<br>
list in groups, then converting each group :<br>
<div><div></div><div class="h5"><br>
> convlist = map conv1 . chunk<br>
><br>
> test = convlist (replicate 8 True ++ replicate 8 False :: [Bool] )<br>
<br>
<br>
</div></div><font color="#888888">David.<br>
</font></blockquote></div><br></div>