Bruno Rijsman
Bruno Rijsman

Reputation: 3807

How do I concatenate two binaries in Erlang?

How do I concatenate two binaries in Erlang?

For example, let's say I have:

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

How do I concatenate B1 and B2 to create a binary B3 which is <<1,2,3,4>>?

The reason I am asking this is because I am writing code to encode a packet for some networking protocol. I am implementing this by writing encoders for the fields in the packet and I need to concatenate those fields to build up the whole packet.

Maybe I am doing this the wrong way. Should I build up the packet as a list of integers and convert the list to a binary at the last moment?

Upvotes: 55

Views: 34484

Answers (5)

cthulahoops
cthulahoops

Reputation: 3835

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!)

Upvotes: 41

Logan Capaldo
Logan Capaldo

Reputation: 40346

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

Upvotes: 8

David N. Welton
David N. Welton

Reputation: 1865

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.

Upvotes: 21

pommonico
pommonico

Reputation: 471

To build on the last answer:

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

Upvotes: 13

Steve Kirsch
Steve Kirsch

Reputation:

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

Upvotes: 130

Related Questions