Having a list of bitstrings, need to join into a single bitstring:
join(Bs) ->
F = fun(B, Bt) -> <<B/bitstring, Bt/bitstring>> end,
lists:foldr(F, <<>>, Bs).
Could you please advise faster way to do this?
You can use a binary comprehension:
join(Bs) = << <<B/bits>> || B <- Bs >>.
For example, try the following in the shell:
1> <<N:16>> = << <<B/bits>> || B <- [<<1:4>>, <<2:4>>, <<3:4>>, <<4:4>>] >>.
<<18,52>>
2> io:format("~.16#~n", [N]).
16#1234
You should probably read about IO Lists. Here is a good blog post on the topic: http://prog21.dadgum.com/70.html I don't know what is it that you are doing, but most of the time you can skip joining binaries altogether. Of course, if you absolutely need to, you can still do that:
5> iolist_to_binary([<<"a">>, <<"b">>, <<"c">>]).
<<"abc">>
And it will work also if some of the elements are strings or chars:
9> iolist_to_binary([<<"a">>, <<"b">>, "c", $d]).
<<"abcd">>
Although RichardC answer is perfect I would add some note. In contrast to lists, when you will join binaries you should prefer making it from head (see Constructing and matching binaries), otherwise you will end up with quadratic behavior. So you can rewrite your code to
join(Bs) ->
F = fun(B, Bt) -> <<Bt/bits, B/bits>> end,
lists:foldl(F, <<>>, Bs).
which will be almost as efficient as bits comprehension. Anyway bits comprehension is simpler and efficient.
join(Bs) -> << <<B/bits>> || B <- Bs >>.