How to join the list of bitstron?

Having a list of bit strings, you need to join one bitstron:

join(Bs) ->
    F = fun(B, Bt) -> <<B/bitstring, Bt/bitstring>> end,
    lists:foldr(F, <<>>, Bs).

Could you advise a faster way to do this?

+4
source share
3 answers

You can use binary understanding:

join(Bs) = << <<B/bits>> || B <- Bs >>.

For example, try the following in a 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
+4
source

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 you are doing, but most of the time you can skip combining binary files altogether. Of course, if you absolutely need it, you can still do it:

5> iolist_to_binary([<<"a">>, <<"b">>, <<"c">>]).
<<"abc">>

And it will work also if some of the elements are strings or characters:

9> iolist_to_binary([<<"a">>, <<"b">>, "c", $d]).
<<"abcd">>
+4

Although RichardC's answer is perfect, I would add a note. Unlike lists, when you join binary files, you should prefer to do it from the head (see Building and matching binary files ), otherwise you will end up with quadratic behavior. So you can rewrite your code on

join(Bs) ->
    F = fun(B, Bt) -> <<Bt/bits, B/bits>> end,
    lists:foldl(F, <<>>, Bs).

which will be almost as efficient as bit recognition. In any case, understanding bits is simpler and more efficient.

join(Bs) -> << <<B/bits>> || B <- Bs >>.
+2
source

All Articles