How to convert a Integer to a ByteString in Haskell

For those, like me, looking for a function to convert an Int or Integer to a ByteString you can use: Data.ByteString.Char8.pack . show Even better if it compiles in your ghc you can use show from TextShow. I understand that this is not quite the OP was asking but people looking for the preceding may end up puzzled at this page due to its title.


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