Decoding bitmask?
Per Gustafsson
<>
Wed Dec 21 16:38:45 CET 2005
Hi
The problem is somewhat underspecified. That is do the optional values
all have the same size? What kind of datastructure would you want to
store the result in?
The solution below assumes that all options have the same size and the
results are returned as a list of two tuples where the first element is
the number of the bit that was set and the second element is the value
of that option.
I have not tested the speed of the two different solutions but I suspect
that the second solution is faster, though I feel that the first one is
prettier.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Solution 1 dealing with the bitmask as a binary
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
decode(<<Man1,Man2,BitMask:2/binary,Rest/binary>>) ->
Options = decode_options(BitMask, Rest, 0),
{Man1,Man2,Options}.
decode_options(BitMask, OptBin, N) when N < 16 ->
Pad = 15-N,
case BitMask of
<<_:N,1:1,_:Pad>> ->
<<OptVal,RestOpts/binary>> = OptBin,
[{N+1, OptVal}|decode_options(BitMask,RestOpts,N+1)];
_ ->
decode_options(BitMask,OptBin,N+1)
end;
decode_options(_BitMask, _OptBin, _N) ->
[].
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% Solution 2 dealing with the bitmask as an integer
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
decode(<<Man1,Man2,BitMask:16,Rest/binary>>) ->
Options = decode_options(BitMask, Rest, 0),
{Man1,Man2,Options}.
decode_options(BitMask, OptBin, N) when N < 16 ->
Mask = 1 bsl (15-N),
case BitMask band Mask of
X when X > 0 ->
<<OptVal,RestOpts/binary>> = OptBin,
[{N+1, OptVal}|decode_options(BitMask,RestOpts,N+1)];
_ ->
decode_options(BitMask,OptBin,N+1)
end;
decode_options(_BitMask, _OptBin, _N) ->
[].
Ericsson wrote:
> Hello!
>
> I'm working on decoding a binary message. The first variables are Mandatory, so they are easy to decode. The last of the mandatory variables is an 16 bit option mask where each bit corresponds to an optional variable that might follow directly after the OptionMask.
>
> How can I decode this OptionMask, and then parse the optional variables, in the cleanest and most "Erlang optimized" way?
>
> <<Mandatory1, Mandatory2, OptionMask:16/binary, Rest/binary>> = Message,
> etc...
>
> /BE
>
>
> This e-mail and any attachment is for authorised use by the intended recipient(s) only. It may contain proprietary material, confidential information and/or be subject to legal privilege. It should not be copied, disclosed to, retained or used by, any other party. If you are not an intended recipient then please promptly delete this e-mail and any attachment and all copies and inform the sender. Thank you.
>
More information about the erlang-questions
mailing list