Jump to content
Main menu
Main menu
move to sidebar
hide
Navigation
Haskell
Wiki community
Recent changes
Random page
HaskellWiki
Search
Search
Create account
Log in
Personal tools
Create account
Log in
Pages for logged out editors
learn more
Contributions
Talk
Editing
Dealing with binary data
(section)
Page
Discussion
English
Read
Edit
View history
Tools
Tools
move to sidebar
hide
Actions
Read
Edit
View history
General
What links here
Related changes
Special pages
Page information
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
===Binary generation=== In contrast to parsing binary data, you might want to generate it. This is the job of the <tt>Put</tt> monad. Follow along with the [http://hackage.haskell.org/package/binary/docs/Data-Binary-Put.html documentation] if you like. The <tt>Put</tt> monad is another state-like monad, but the state is an offset into a series of buffers where the generated data is placed. All the buffer creation and handling is done for you, so you can just forget about it. It results in a lazy bytestring (so you can generate outputs that are larger than memory). Here's the reverse of our simple <tt>Get</tt> example: <haskell>import qualified Data.ByteString.Lazy as BL import Data.Binary.Put serialiseSomething :: Put serialiseSomething = do putWord32be 1 putWord16be 2 putWord8 3 main :: IO () main = BL.putStr $ runPut serialiseSomething</haskell> And running it shows that it's generating the correct serialisation: <pre>% runhaskell /tmp/example.hs| hexdump -C 00000000 00 00 00 01 00 02 03 |.......|</pre> If you want the output of <tt>runPut</tt> to be a strict bytestring, you just need to convert it with <hask>B.concat $ BL.toChunks $ runPut xyz</hask>. One limitation of <tt>Put</tt>, due to the nature of the <tt>Builder</tt> monad which it works with, is that you can't get the current offset into the output. This can be an issue with some formats which require you to encode byte offsets into the file. You have to calculate these byte offsets yourself.
Summary:
Please note that all contributions to HaskellWiki are considered to be released under simple permissive license (see
HaskellWiki:Copyrights
for details). If you don't want your writing to be edited mercilessly and redistributed at will, then don't submit it here.
You are also promising us that you wrote this yourself, or copied it from a public domain or similar free resource.
DO NOT SUBMIT COPYRIGHTED WORK WITHOUT PERMISSION!
Cancel
Editing help
(opens in new window)
Toggle limited content width