如何解析Clojure中的二进制文件 [英] how to parse binary files in Clojure

查看:174
本文介绍了如何解析Clojure中的二进制文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在clojure中解析二进制数据的最干净的方法是什么?
我需要能够同样干净地读/写文件或套接字。


例如:

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.

推荐答案

光泽<

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"})

bit-map 函数允许位级格式,但定义的位数必须被8整除,因此字节仍然排成一行。

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.

还有字节规格

这篇关于如何解析Clojure中的二进制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆