How do I concatenate two binaries in Erlang?

隐身守侯 提交于 2019-11-28 18:07:41

The answer is don't. gen_tcp:send will accept deep lists. So, concatenation is simply:

B3 = [B1, B2].

This is O(1). In general, when dealing with this sort of data always build up deep list structures and let the io routines walk the structure at output. The only complication is that any intermediate routines will have accept deep lists.

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

To use an io_list, you could do:

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

Which is nice and legible. You could also use lists and things in there if it's more convenient.

To build on the last answer:

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

use the erlang function list_to_binary(List) you can find the documentation here: http://www.erlang.org/documentation/doc-5.4.13/lib/kernel-2.10.13/doc/html/erlang.html#list_to_binary/1

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!