4 ms·
The page covers this further down -- you can "bind" and then "use" a size [0]: <<Sz:8,Payload:Sz/binary-unit:8,Rest/binary>> This bit syntax binds `Sz` as a
by lsllc 5y ago
The page covers this further down -- you can "bind" and then "use" a size [0]:
<<Sz:8,Payload:Sz/binary-unit:8,Rest/binary>>
This bit syntax binds `Sz` as an 8-bit length value, `Payload` as `Sz` 8-bit bytes with the remainder in `Rest`.
[0] https://www.erlang.org/doc/programming_examples/bit_syntax.html#binding-and-using-a-size-variable https://www.erlang.org/doc/programming_examples/bit_syntax.h...
- dhx 5y agoThanks for the example. Is there a way to perform a positive and negative look-ahead instead of just reading the remaining data to end of input?
- eproxus 5y agoYou also have Erlang’s pattern matching at your disposal: decode(<<16#01, Size:8, Payload:Size/binary-unit:8, Rest/binary>>) -> [{field1, Payload}|decode(Rest)]; decode(<<16#02, Flags:16, Rest/binary>>) when Flags =:= 1 -> [{field2, true}|decode(Rest)]; decode(<<16#02, Flags:16, Rest/binary>>) -> [{field2, false}|decode(Rest)]. Anything after the when keyword is a guard condition allowing for some manner of positive/negative “look ahead” (Contrived example, but maybe you get the point).
- lsllc 5y agoYes, this is exactly how you do it, with pattern matching & guards!