在 clojure 中解析二进制数据的最简洁方法是什么?我需要能够同样干净地读取/写入文件或套接字。
就像是:
(读取数据源数据) => { :index 42 , :block-size 4 , 数据大小: 31415, :data (1 2 3 4 ...)}
和相反的数据放回。以某种方式定义一次结构并让读写函数使用相同的定义真的很棒。
在 clojure 中解析二进制数据的最简洁方法是什么?我需要能够同样干净地读取/写入文件或套接字。
就像是:
(读取数据源数据) => { :index 42 , :block-size 4 , 数据大小: 31415, :data (1 2 3 4 ...)}
和相反的数据放回。以某种方式定义一次结构并让读写函数使用相同的定义真的很棒。
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.
既然 Clojure 可以使用原生 Java 函数,为什么不使用它们呢?沿着这些思路快速搜索一下:http: //gnuvance.wordpress.com/2009/01/29/reading-binary-data-in-clojure/