[erlang-questions] binary expression with fixed and variablefields

info <>
Thu Jul 1 18:49:08 CEST 2010




On Tue, Jun 29, 2010 at 7:22 PM, info <> 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

The general question is: shall I use the bit syntax to extract each field or shall I use the token method ?
After extraction with the bit syntax, each field will be integer. I must convert again in string if I want to compare with something. I don't see what I win or what I lost !
What is the more efficient in Erlang ? I read in this forum to evict the string syntax because of the "bad" representation of the char in erlang.


<<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
How can I know if the field3 is empty? by the size of the full string. But if 2 fields are empty, it's impossible.
And if the field3 and the field4 are empty, you will have four versions in your case (2 power N) !

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>>

What is "better" in Erlang: "," or _:8


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