How to combine two binary files in Erlang?

How to combine two binaries in Erlang?

For example, let's say I have:

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

How to combine B1 and B2 to create a binary B3 that is <1,2,3,4 โ†’?

I ask for this because I am writing code to encode a packet for some kind of network protocol. I implement this by writing encoders for the fields in the package, and I need to combine these fields to create the whole package.

Maybe I'm doing it wrong. Should I create a package as a list of integers and convert the list to binary at the last moment?

+48
erlang binaries
Mar 01 '09 at 22:11
source share
5 answers

The answer is no. gen_tcp: send will accept deep lists. So concatenation is simple:

 B3 = [B1, B2]. 

This is O (1). In general, when working with such data types, deep list structures are always created and io-procedures are allowed to move through the structure at the output. The only complication is that any intermediate routines will accept deep lists.

+32
Mar 01 '09 at 23:40
source share
 28> B1= <<1,2>>. <<1,2>> 29> B2= <<3,4>>. <<3,4>> 30> B3= <<B1/binary, B2/binary>>. <<1,2,3,4>> 31> 
+119
Mar 02 '09 at 7:03
source share

To use io_list you can do:

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

This is good and legible. You can also use lists and things there if it is more convenient.

+16
Feb 19 '14 at 15:38
source share

To build on the last answer:

 bjoin(List) -> F = fun(A, B) -> <<A/binary, B/binary>> end, lists:foldr(F, <<>>, List). 
+12
Dec 17 '09 at 19:54
source share

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/ one

+8
Mar 01 '09 at 22:14
source share



All Articles