construct binary
Stephen Han
<>
Thu Jul 7 21:58:47 CEST 2005
Hi
Thanks guys... This is great example how to use bit syntax elegantly
not just for my problem for any bit related problems... thank you so
much...
If you look at my code, you will know why I was so frustrated... I
always feel it is not right but I used it. I will attach mine although
it is embarrassing. I am brave enough to post mine to show which is
elegant and which is not for the sake of Erlang community. :-(
-module(eprl).
-compile (export_all).
pack( Channels ) ->
Num = length(Channels),
pack_num(Num, pack_channel(Num, Channels)).
reserve(1) -> 0; reserve(2) -> 5;
reserve(3) -> 2; reserve(4) -> 7;
reserve(5) -> 4; reserve(6) -> 1;
reserve(7) -> 6; reserve(8) -> 3;
reserve(N) when N > 0 -> reserve( N - 8 ).
pack_num(N, B) ->
R1 = reserve(N),
R2 = reserve(N+1),
L = ((size(B)-1) * 8 - R2),
<< B1:8, B2:L, _:R2 >> = B,
<< N:5, B1:8, B2:L, 0:R1 >>.
pack_channel(1, [A1]) ->
<< A1:11, 0:5 >>;
pack_channel(2, [A1, A2]) ->
<< A1:11, A2:11, 0:2 >>;
pack_channel(3, [A1, A2, A3]) ->
<< A1:11, A2:11, A3:11, 0:7 >>;
pack_channel(4, [A1, A2, A3, A4]) ->
<< A1:11, A2:11, A3:11, A4:11, 0:4 >>;
pack_channel(5, [A1, A2, A3, A4, A5]) ->
<< A1:11, A2:11, A3:11, A4:11, A5:11, 0:1 >>;
pack_channel(6, [A1, A2, A3, A4, A5, A6]) ->
<< A1:11, A2:11, A3:11, A4:11, A5:11, A6:11, 0:6 >>;
pack_channel(7, [A1, A2, A3, A4, A5, A6, A7]) ->
<< A1:11, A2:11, A3:11, A4:11, A5:11, A6:11, A7:11, 0:3 >>;
pack_channel(8, [A1, A2, A3, A4, A5, A6, A7, A8]) ->
<< A1:11, A2:11, A3:11, A4:11, A5:11, A6:11, A7:11, A8:11 >>;
pack_channel(N, [A1, A2, A3, A4, A5, A6, A7, A8|T]) when N > 0 ->
B1 = << A1:11, A2:11, A3:11, A4:11, A5:11, A6:11, A7:11, A8:11 >>,
B2 = pack_channel(N-8, T),
list_to_binary([B1, B2]).
regards,
On 7/7/05, Vance Shipley <> wrote:
> Mathias,
>
> I'd have to say that your version is much better as it's shorter
> and simpler. Not to mention the fact that, as you pointed out,
> my pad calculation was flawed. The one difference though is that
> my version didn't create a new binary so would presumably be more
> efficient.
>
> -Vance
>
> On Thu, Jul 07, 2005 at 08:54:43AM +0200, Matthias Lang wrote:
> }
> } decode(<<N_channels:5, Alignment_bits:3, Tail/binary>>) ->
> } decode2(N_channels, <<Alignment_bits:3, Tail/binary, 0:5>>).
> } decode2(0, _) ->
> } [];
> } decode2(N, <<C:11, A:5, T/binary>>) ->
> } [C|decode2(N-1, <<A:5, T/binary, 0:3>>)].
>
More information about the erlang-questions
mailing list