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">>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With