如何在Erlang中连接两个二进制文件?

pgccezyw  于 2022-12-08  发布在  Erlang
关注(0)|答案(5)|浏览(181)

如何在Erlang中连接两个二进制文件?
例如,假设我有:

B1 = <<1,2>>.
B2 = <<3,4>>.

我如何连接B1和B2以创建〈〈1,2,3,4〉〉的二进制B3?
我问这个问题的原因是因为我正在为某个网络协议编写编码数据包的代码。我通过为数据包中的字段编写编码器来实现这一点,我需要将这些字段连接起来以构建整个数据包。
也许我的方法不对,我应该把数据包构建成一个整数列表,然后在最后一刻把这个列表转换成二进制吗?

nwsw7zdq

nwsw7zdq1#

28> B1= <<1,2>>.
<<1,2>>
29> B2= <<3,4>>.
<<3,4>>
30> B3= <<B1/binary, B2/binary>>.
<<1,2,3,4>>
31>
kxe2p93d

kxe2p93d2#

You can concatenate binaries using bit syntax:

1> B1 = <<1,2>>.
<<1,2>>
2> B2 = <<3,4>>.
<<3,4>>
3> B3 = <<B1/binary, B2/binary>>.
<<1,2,3,4>>

In many cases, particularly where the data is destined for the network you can avoid the concatenation by constructing an io_list instead.

B3 = [B1, B2],
gen_tcp:send(Socket, B3).

This is O(1) as it avoids copying either binary. gen_tcp:send will accept the deep list and walk the structure for output. (A two element list takes very little additional memory, so the memory overhead is small.)
In some cases (repeated appends to the same binary), Erlang now has optimisations that avoid copying the binary being appended to so using io_lists may be less relevant: http://erlang.org/doc/efficiency_guide/binaryhandling.html#constructing-binaries
Historical note: I originally advised only the io_list solution and a lot of commenters correctly point out that I failed to answer the question. Hopefully, the accepted answer is now complete. (11 years later!)

bn31dyow

bn31dyow3#

要使用io_list,可以执行以下操作:

erlang:iolist_to_binary([<<"foo">>, <<"bar">>])

这是很好的和清晰的。你也可以使用清单和东西在那里,如果它更方便。

lnxxn5zx

lnxxn5zx4#

在最后一个答案的基础上:

bjoin(List) ->
    F = fun(A, B) -> <<A/binary, B/binary>> end,
    lists:foldr(F, <<>>, List).
eni9jsuy

eni9jsuy5#

使用erlang函数list_to_binary(List),您可以在此处找到文档:http://www.erlang.org/documentation/doc-5.4.13/lib/kernel-2.10.13/doc/html/erlang.html#list_to_binary/1

相关问题