views:

1411

answers:

4

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?

+6  A: 

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.

cthulahoops
Thanks! I was not familiar with the concepts of deep lists and io lists in Erlang.
Cayle Spandon
+10  A: 
28> B1= <<1,2>>.
<<1,2>>
29> B2= <<3,4>>.
<<3,4>>
30> B3= <<B1/binary, B2/binary>>.
<<1,2,3,4>>
31>
Presumably this is not an O(1) operation, so it would still make sense to build a deep list (IO list) as suggested by cthulahoops and postpone walking the deep list until I am ready to send the packet?
Cayle Spandon
A: 

To build on the last answer:

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