[erlang-questions] Real basic binary manipulation question

Steve Davis steven.charles.davis@REDACTED
Sat Jan 17 11:46:10 CET 2009


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



More information about the erlang-questions mailing list