[erlang-questions] Real basic binary manipulation question

Per Gustafsson <>
Sat Jan 17 15:30:34 CET 2009


Or even more straight-forward:

-module(zrle).
-export([decompress/1]).

decompress(Bin) when is_binary(Bin) ->
    decompress(Bin, <<>>).

decompress(<<0, Count, Tail/binary>>, Acc) ->
    decompress(Tail, <<Acc/binary, 0:(Count * 8)>>);
decompress(<<Head, Tail/binary>>, Acc) ->
    decompress(Tail, <<Acc/binary, Head>>);
decompress(<<>>, Acc) ->
    Acc.

If you are using at least R12 the performance for this should be ok.

Per

Juan Jose Comellas wrote:
> In your function it wasn't clear to me why you were adding the 
> 'expand' atom to the destination list T. Maybe something like this 
> could do:
>
>
> -module(zrle).
> -export([decompress/1]).
>
> decompress(Bin) when is_binary(Bin) ->
>     decompress(Bin, []).
>
> decompress(<<0, Count, Tail/binary>>, Acc) ->
>     decompress(Tail, [<<0:(Count * 8)>> | Acc]);
> decompress(<<Head, Tail/binary>>, Acc) ->
>     decompress(Tail, [Head | Acc]);
> decompress(<<>>, Acc) ->
>     list_to_binary(lists:reverse(Acc)).
>
>
> e.g.
>
> 1> zrle:decompress(<<1, 0, 5, 2, 3, 4, 0, 3>>).
> <<1,0,0,0,0,0,2,3,4,0,0,0>>
>
>
>
> On Sat, Jan 17, 2009 at 8:46 AM, Steve Davis 
> < 
> <mailto:>> wrote:
>
>     Problem - to decompress a binary where zeros are run-length encoded.
>     The following seems to work but also seems ugly and causes unnecessary
>     overhead.
>
>     %% Decompress binary where Zeros are Run-Length Encoded
>     decompress(Bin) when is_binary(Bin) ->
>            L = binary_to_list(Bin),
>            F = fun(X, [H|T]) when H =:= expand -> lists:duplicate(X,
>     0) ++ T;
>                            (X, Acc) when X =:= 0 -> [expand] ++ Acc;
>                            (X, Acc) -> [X] ++ Acc
>                    end,
>            Decompressed = lists:foldl(F, [], L),
>            list_to_binary(lists:reverse(lists:flatten(Decompressed))).
>
>     Any bids on an improvement?
>
>     Thanks for any attention.
>
>     Side note: the erlang bit syntax is *amazing* when you actually get
>     down to doing something with IP packets
>     _______________________________________________
>     erlang-questions mailing list
>      <mailto:>
>     http://www.erlang.org/mailman/listinfo/erlang-questions
>
>
> ------------------------------------------------------------------------
>
> _______________________________________________
> erlang-questions mailing list
> 
> http://www.erlang.org/mailman/listinfo/erlang-questions




More information about the erlang-questions mailing list