Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a Integer to a ByteString in Haskell

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!

like image 621
Johannes Weiss Avatar asked Feb 17 '10 17:02

Johannes Weiss


People also ask

What is ByteString in Haskell?

ByteString is used to represent bytes of string in Haskell. ByteString is used when we want high performance, high-speed requirement, etc. ByteString is also known as time and space-efficient implementation. ByteString contains 8-bit character data.


1 Answers

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).

like image 153
Don Stewart Avatar answered Sep 17 '22 22:09

Don Stewart