天天看點

【原創】Erlang 中 binary_to_term 和 term_to_binary 的使用場景

在《erlang程式設計》第五章中有如下說明:

@spec term_to_binary(term) -> bin 

      該函數可以将任何 erlang 項式轉化為相應的二進制資料。而轉換得到的二進制資料是以所謂的“外部資料格式”存儲的。這種資料可以用于檔案存儲、網絡傳輸等。而且在轉換之後,還可以從這些二進制資料中還原出原始的資料項。該函數在需要對複雜的資料結構進行檔案存儲和網絡傳輸時極為有用。 

在《erts-x.x.x》的 reference manual -> erlang 中有如下說明: 

<a href="http://my.oschina.net/moooofly/blog/281986#">?</a>

1

2

3

4

5

6

7

<code>term_to_binary(term) -&gt; ext_binary()</code>

<code>types:</code>

<code>    </code><code>term = term()</code>

<code>returns a binary data object</code><code>which</code> <code>is the result of encoding term according to the erlang external term</code><code>format</code><code>.</code>

<code>根據 erlang 外部項式格式對 term 進行編碼,傳回相應的二進制資料對象</code>

<code>this can be used</code><code>for</code> <code>a variety of purposes,</code><code>for</code> <code>example writing a term to a</code><code>file</code> <code>in</code> <code>an efficient way, or sending</code>

<code>an erlang term to some</code><code>type</code> <code>of communications channel not supported by distributed erlang.</code>

erlang:term_to_binary/1,2 函數傳回值是 erlang 擴充 term 格式 (erlang external term format) 的 binary,即 ext_binary() 。 這個函數能把 erlang 資料封裝成二進制流,是一種存儲和傳輸 erlang 資料的有效途徑,甚至可以用這種封包/解包方式用作 socket 的通信協定(某頁遊項目就是這麼幹的)。