Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Bits to Int8 Haskell

Trying to convert a list of Bits (0,1) into an Int8 or something similar so that I am not wasting a byte from ByteString on only 1 bit

For example, I may have a list like [0,1,0,0,0,1,1,1,1,0], which as a ByteString represents each of those as a Byte instead of a Bit.

like image 930
astiefel Avatar asked Mar 08 '26 15:03

astiefel


1 Answers

One solution would be to just fold over the list:

import Data.Bits (Bits, shiftL, (.|.))

pack :: (Num b, Foldable t, Bits b) => t b -> b
pack a = foldl go 0 a
    where go acc i = (acc `shiftL` 1) .|. i

and you get:

\> pack [0,1,0,0,0,1,1,1,1,0]
286
like image 127
behzad.nouri Avatar answered Mar 11 '26 07:03

behzad.nouri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!