Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to join list of bitstrings?

Tags:

erlang

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?

like image 731
taro Avatar asked Dec 29 '13 19:12

taro


2 Answers

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
like image 72
RichardC Avatar answered Oct 16 '22 09:10

RichardC


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">>
like image 21
loxs Avatar answered Oct 16 '22 09:10

loxs