我知道如何将列表分为两部分-(a1, rest) = splitAt N myList
。但是使用ByteString
它将不起作用,因为我们使用位而不是字节进行操作。
如何从ByteString
中获取N位?或将其分为两部分,第一部分应为N位大小。
Data.Bits
提供按位运算:https://hackage.haskell.org/package/base-4.12.0.0/docs/Data-Bits.html您可以先使用splitAt
和word8将字节字符串分成2个字节字符串,然后使用testBit
和shiftL
/ shiftR
]逐位读取word8
type Frag = ([Bool], ByteString, [Bool])
splitBS :: Int -> ByteString -> (Frag, Frag)
splitBS bits bs =
let (byte, remb) = bits `quotRem` 8
(bs1, t) = splitAt byte bs
w = head t
bs2 = tail t
(b1, b2) = splitWord remb w
in (([], bs1, b1), (b2, bs2, []))
fromBits :: Bits a => a -> [Bool]
fromBits b
| b == zeroBits = []
| otherwise = testBit b 0 : fromBits (shiftR b 1)
fromBits' :: Bits a => a -> [Bool]
fromBits' = reverse . fromBits
splitWord :: Int -> Word -> ([Bool], [Bool])
splitWord n w =
let bl = fromBits w
in (take n bl, drop n bl)