[erlang-questions] binary expression with fixed and variable fields

Antoine Koener antoine.koener@REDACTED
Thu Jul 1 14:18:33 CEST 2010


On Tue, Jun 29, 2010 at 7:22 PM, info <info@REDACTED> wrote:

> Hi all,
> I have a string composed of several fixed and variable fields. I would like
> to parse this string as binary expression.
> I checked the example with an IP datagram (the variable fields are to the
> end ...):
>
>  <<field1:size1,field2:size2,field3:size3,field4:size4,field5:size5>>
>
> If the size3 of the field3 is variable,how to parse the string ?
>

Fields Size must be determined before the match or within the match.
see http://erlang.org/doc/programming_examples/bit_syntax.html#id2261909


>
> <<field1:size1,field2:size2,Rest/binary>>  but after ?
>
> If a field is empty, how to detect it ?
>

Use another binary expression.

case Bin of
  <<VersionWithField3>> ->
   ;
 <<VersionWithout>> ->
  ;
  _ -> % catch all others
    ok
end


> If a char (e.g comma) is between each field, is it always possible to use
> the binary syntax ?
>

Just use the "," notation:

<<field1:size1,",",field2:size2,",",Rest/binary>>

Long binary strings are used whenever the binary holds enough information
for itself,
when you need to "parse" and not "match" you may use smaller binary strings.

Taken from some kind of code of mine:

-define( UINT32(X), X:32/native-unsigned).
-define( UINT16(X), X:16/native-unsigned).

action(5522146, _Function, <<
?UINT32(Hwnd),
?UINT16(Size),
Title:Size/binary,
?UINT32(X),
?UINT32(Y),
?UINT32(Cx),
?UINT32(Cy)>>, Pid) ->

%io:format("~p: ~s, ~p ~p ~p~n", [?MODULE, Function, Pid, Hwnd, Title ]),

my 2 cents.


More information about the erlang-questions mailing list