[erlang-questions] bit syntax feature request

Serge Aleynikov saleyn@REDACTED
Sat Jul 28 15:11:36 CEST 2007


When parsing some protocols I run into cases when I needed to convert 
parts of a binary to strings (i.e. lists).  Unfortunately current bit 
syntax expressions don't support Value:Size/string or Value:Size/list types:

Ei = Value |
      Value:Size |
      Value/TypeSpecifierList |
      Value:Size/TypeSpecifierList

Type = integer | float | binary
     The default is integer.


Example:

I need to parse an integer, and string from a binary:

1> <<X:16/integer, S1:3/binary, _/binary>> = <<1,2,$a,$b,$c,$d,3,4>>.
<<1,2,97,98,99,100,3,4>>
2> S = binary_to_list(S1).
"abc"

what I'd like to be able to do is:

1> <<X:16/integer, S:3/string, _/binary>> = <<1,2,$a,$b,$c,$d,3,4>>.
<<1,2,97,98,99,100,3,4>>

2> io:format("~p, ~p\n", [X, S]).
258, "abc".

When most parts of the binary are strings, it becomes quite verbose to 
introduce many binary_to_list/1 calls and diminishes the value of 
pattern matching syntax.

Any particular reason this is not currently implemented?  If not, how 
hard would it be to add such a feature?

Serge



More information about the erlang-questions mailing list