[erlang-questions] Real basic binary manipulation question

Juan Jose Comellas juanjo@REDACTED
Sat Jan 17 14:30:31 CET 2009


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 <steven.charles.davis@REDACTED
> 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
> erlang-questions@REDACTED
> http://www.erlang.org/mailman/listinfo/erlang-questions
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20090117/81b949e7/attachment.htm>


More information about the erlang-questions mailing list