如何从 ByteString 中获取第 n 个字节?

How to get nth byte from ByteString?

如何在 Haskell 中获取 ByteString 的第 n 个字节?

我试图为 ByteString 找到类似 !! 的函数,但一无所获。

ByteString.index 是您要查找的函数。

大多数 "containerish" 类型模拟扩展列表接口;您还需要小心,因为如果您向 index 函数提供一个太短的字符串(普通列表中的 !! 也会使程序崩溃),程序就会崩溃。更好的实现可能是

import Data.ByteString as B
nthByte :: Int -> B.ByteString -> Maybe Word8
nthByte n bs = fst <$> B.uncons (B.drop n bs)

从里到外读取,丢弃前 n 个字节(可能产生空字节字符串),然后尝试将第一个字符与其余字符分开,如果成功,忽略字符串的其余部分。