如何将整数转换为Haskell中的ByteString [英] How to convert a Integer to a ByteString in Haskell

查看:105
本文介绍了如何将整数转换为Haskell中的ByteString的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们希望以特定的二进制格式序列化数据。我们在内部使用 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.ByteStrings 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 Integers to ByteStrings (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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆