Haskell 字节串打包/解包

发布于 2024-11-30 02:40:39 字数 444 浏览 5 评论 0原文

我仍然不明白字节串是如何工作的,

import qualified Data.ByteString.Lazy as BS
let x = BS.readFile "somefile.txt" --some large file
let z = ((reverse (BS.unpack x)) !! 2) --do stuff here

我知道字节串可以用来非常快速有效地读取大量数据。但拆开包装是没有意义的。

let z = readArray x 1 --can you read the bytestring like its a array?(something like this)

不解压就不能直接读取字节串形式的数据吗?或者只是解压一部分数据?

您能解释一下它是如何工作的吗?(代码示例)

I still don't get how bytestrings work

import qualified Data.ByteString.Lazy as BS
let x = BS.readFile "somefile.txt" --some large file
let z = ((reverse (BS.unpack x)) !! 2) --do stuff here

I know bytestrings can be used to read large amounts of data ,very quickly and efficiently. But unpacking a packing doesn't make sense.

let z = readArray x 1 --can you read the bytestring like its a array?(something like this)

Can't you just read the data in bytestring form without unpacking? or just unpack a segment of the data?

Could you explain how it all works?(Code examples)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

甜嗑 2024-12-07 02:40:39

但是打包和拆包没有任何意义。

嗯,这当然是浪费。

不解压直接读取字节串形式的数据不行吗?

  • 您的意思是对数据进行操作而不将其转换为另一种形式吗?当然可以。具体如何取决于你想做什么。我使用 FFI(以及后来的 Data.Vector.Storable)将 ByteString 作为一组 Word32 进行访问。您可以自然地提取任何单独的 Word8。我确信您已经看过 ByteString 的 Haddock 文档,但知道其他包直接使用字节串(例如:用于与通过 FFI 调用的 C 代码进行图像缓冲区通信)。

  • 您的意思是“不使用[Word8][Char]对数据进行操作”吗?二进制、谷物和其他包可用于将字节串解析为任意类型。

或者只是解压一部分数据?

当然:

import Data.ByteString as B

getPortion n m = B.unpack . B.take n . B.drop m

But packing a unpacking doesn't [make] sense.

Well, it's certainly wasteful.

Can't you just read the data in bytestring form without unpacking?

  • Do you mean operate on the data without converting it to another form? Sure you can. Exactly how depends on what you want to do. I've used FFI (and later, Data.Vector.Storable) to access the ByteString as a set of Word32's. You can pull out any individual Word8 naturally. I'm sure you've seen ByteString's Haddock documents, but know that other packages consume bytestrings directly (ex: for communicating an image buffer with C code that is called via FFI).

  • Do you mean "operate on the data without using [Word8] or [Char]"? The binary, cereal, and other packages can be used to parse bytestrings into arbitrary types.

or just unpack a segment of the data?

Sure:

import Data.ByteString as B

getPortion n m = B.unpack . B.take n . B.drop m
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文