如何将整数转换为Haskell中的ByteString [英] How to convert a Integer to a ByteString in Haskell
问题描述
Data.ByteString
s。所以问题是:如何将不同的数据类型用于 ByteString
。对于 String
我们没有问题,我们可以使用 encodeLazyByteString UTF8string
。但我们还想将整数
s转换为 ByteString
s(big-endian)。 有人知道如何做到这一点,或者有任何使用Haskell和二进制格式的好技巧? 谢谢!
Data.Binary的完美工作:
前奏> :m + Data.Binary
Prelude Data.Binary>编码(pi :: Double)
组块251!\EM\255\255\255\255\255\255\255\205清空
Prelude Data.Binary>编码(42 ::整数)
块\NUL\NUL\NUL\NUL *空
生成懒惰的字节串,当然可以将其转换为严格的字节串。谷歌包提供了很多相同的接口,但只产生严格的字节串(所以没有无限的编码流)。
We'd like to serialize data in a specific binary format. We use Data.ByteString
s internally.
So, the question is: How to convert the different data types we use to a ByteString
. For String
we have no problem, we can use encodeLazyByteString UTF8 "string"
. But we'd also like to convert Integer
s to ByteString
s (big-endian).
Does anyone know how to do that and/or has any good tips using Haskell and binary formats?
Thanks!
A perfect job for Data.Binary:
Prelude> :m + Data.Binary
Prelude Data.Binary> encode (pi :: Double)
Chunk "\SOH\SOH\NUL\NUL\NUL\NUL\NUL\NUL\NUL\a\CAN-DT\251!\EM\255\255\255\255\255\255\255\205" Empty
Prelude Data.Binary> encode (42 :: Integer)
Chunk "\NUL\NUL\NUL\NUL*" Empty
to yield lazy bytestrings, which can of course be converted to strict ones. The cereal package provides much the same interface, but yields strict bytestrings only (so no infinite streaming of encodings).
这篇关于如何将整数转换为Haskell中的ByteString的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!