how to parse binary files in Clojure
Asked Answered
C

2

10

What is the cleanest way to parse binary data in clojure? I need to be able to read/write equally cleanly to a file or a socket.

something like:

  (read-data source-of-data) 
  => { :index 42 , :block-size 4 , data-size: 31415, :data (1 2 3 4 ...)}

and the reverse for putting data back. It would be really great to somehow define the structure once and have the read and write functions use the same definition.

Charlton answered 15/4, 2009 at 0:34 Comment(0)
H
13

Gloss makes it easy to define binary formats at the byte level for both reading and writing.

(defcodec example-codec
  [:id       :uint32
   :msg-type (enum :byte {:a \A, :b \B})
   :status   (string :ascii :length 11)])

(def buffer (byte-array 16))

(.read (input-stream "filename.bin") buffer)
(decode example-codec buffer)

(encode example-codec {:id 42, :msg-type :a, :status "A-OKAY"})

The bit-map function allows bit level formats, but the number of bits defined must be divisible by 8 so the bytes still line up.

There's also byte-spec.

Harvin answered 26/10, 2011 at 5:32 Comment(0)
H
4

Since Clojure can use native Java functions, why not use those? A quick Googling along those lines gives: http://gnuvince.wordpress.com/2009/01/29/reading-binary-data-in-clojure/

Heaume answered 15/4, 2009 at 19:52 Comment(1)
I need to both read and write these fomats though this is a good start. I also need bit level accuracy.Charlton

© 2022 - 2024 — McMap. All rights reserved.