如何从ByteString中获取N位?

问题描述 投票:0回答:1

我知道如何将列表分为两部分-(a1, rest) = splitAt N myList。但是使用ByteString它将不起作用,因为我们使用位而不是字节进行操作。

如何从ByteString中获取N位?或将其分为两部分,第一部分应为N位大小。

haskell binary binary-data
1个回答
0
投票

Data.Bits提供按位运算:https://hackage.haskell.org/package/base-4.12.0.0/docs/Data-Bits.html您可以先使用splitAt和word8将字节字符串分成2个字节字符串,然后使用testBitshiftL / 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)
© www.soinside.com 2019 - 2024. All rights reserved.