# [erlang-questions] Interleave binaries

Hynek Vychodil hynek@REDACTED
Mon Aug 8 13:34:43 CEST 2011

```Sorry, I have accidentally forgot remove one line from code. The
correct version should be:

il(A, B) when is_binary(A), is_binary(B), size(A) =:= size(B) -> il(A, B, <<>>).

il(<<A:16,RestA/binary>>, <<B:16,RestB/binary>>, Acc) ->
il(RestA, RestB, <<Acc/binary,A:16, B:16>>);
il(<<>>, <<>>, Acc) -> Acc.

You can experiment with some loop unrolling like inserting this clause
on begin of il/3 and experiment with length of this unrolling

il(<<A1:16, A2:16, A3:16, A4:16, RestA/binary>>, <<B1:16, B2:16,
B3:16, B4:16, RestB/binary>>, Acc) ->
il(RestA, RestB, <<Acc/binary, A1:16, B1:16, A2:16, B2:16, A3:16,
B3:16, A4:16, B4:16>>);

if it is not fast enough for you then try write NIF.

On Sat, Aug 6, 2011 at 10:06 AM, Hynek Vychodil <hynek@REDACTED> wrote:
> It would not be so much efficient because it would make stack for
> every two bytes of input. Much more efficient will be
>
> il(A, B) when is_binary(A), is_binary(B), size(A) =:= size(B) -> il(A, B, <<>>).
>
> il(<<A:16,RestA/binary>>, <<B:16,RestB/binary>>, Acc) ->
>    Rest=il(RestA, RestB),
>    il(RestA, RestB, <<Acc/binary,A:16, B:16>>);
> il(<<>>, <<>>, Acc) -> Acc.
>
> See http://www.erlang.org/doc/efficiency_guide/binaryhandling.html#id64529
>
>
> On Sat, Aug 6, 2011 at 6:40 AM, Wes James <comptekki@REDACTED> wrote:
>> Hi,
>>
>> On Fri, Aug 5, 2011 at 3:26 PM, Bob Cowdery <bob@REDACTED> wrote:
>>> Hi
>>>
>>> I'm wanting to interleave two binaries.
>>>
>>> Bin1 = <<0,1>>,
>>> Bin2 = <<2,3>>,
>>> << <<A,B,C,D>> || <<A,B>> <= Bin1, <<C,D>> <= Bin2 >>.
>>> <<0,1,2,3>>
>>>
>>> Bin1 = <<0,1,2,3>>,
>>> Bin2 = <<4,5,6,7>>,
>>> << <<A,B,C,D>> || <<A,B>> <= Bin1, <<C,D>> <= Bin2 >>.
>>> <<0,1,4,5,0,1,6,7,2,3,4,5,2,3,6,7>>
>>>
>>> whereas I want:
>>> <<0,1,4,5,2,3,6,7>>
>>
>> <snip>
>>
>> I don't know if this will suffice:
>>
>> -------------------------------------------------
>>
>> % interleave module
>>
>> -module(ilm).
>>
>> -export([il/2]).
>>
>> % interleave function
>>
>> il(<<A1,A2,RestA/binary>>, <<B1,B2,RestB/binary>>) ->
>>    Rest=il(RestA, RestB),
>>    <<A1, A2, B1, B2, Rest/binary>>;
>>
>> il(<<>>, <<>>) -> <<>>.
>>
>> -----------------------------------------------
>>
>> Erlang R14B02 (erts-5.8.3) [source] [smp:2:2] [rq:2] [async-threads:0]
>> [hipe] [kernel-poll:false]
>>
>> Eshell V5.8.3  (abort with ^G)
>> 1> c(ilm).
>> {ok,ilm}
>> 2> ilm:il(<<0,1,2,3>>, <<4,5,6,7>>).
>> <<0,1,4,5,2,3,6,7>>
>>
>> ----------------------------------------------
>>
>> -wes
>> _______________________________________________
>> erlang-questions mailing list
>> erlang-questions@REDACTED
>> http://erlang.org/mailman/listinfo/erlang-questions
>>
>
>
>
> --
> --Hynek (Pichi) Vychodil
>
> your boss.  Be a data hero!
>

--
--Hynek (Pichi) Vychodil