However, I ran across some other cool tidbits. If M is a 16 bit binary value, you can unpack the first 3 bits into X, the next 7 bits into Y, and the last 6 bits into Z using the syntax:
<<X:3, Y:7, Z:6>> = MHence, you can parse an IPv4 datagram in a single pattern-matching operation (taken from "Programming Erlang: Software for a Concurrent World" p. 99):
-define(IP_VERSION, 4).That's about as cool as it gets for implementing binary protocols!
-define(IP_MIN_HDR_LEN, 5).
...
DgramSize = size(Dgram),
case Dgram of
<<?IP_VERSION:4, HLen:4, SrvcType:8, TotLen:16,
ID:16, Flgs:3, FragOff:13,
TTL:8, Proto:8, HdrChkSum:16,
SrcIP:32,
DestIP:32, RestDgram/binary>> when HLen >= 5, 4*HLen =< DgramSize ->
OptsLen = 4*(HLen - ?IP_MIN_HDR_LEN),
<<Opts:OptsLen/binary,Data/binary>> = RestDgram,
...


7 comments:
About '%' for comments: AFAIK, Erlang was born as Prolog-metainterpreter, and in Prolog comments start with '%'.
Binary syntax is cool, agreed.
% is also the comment character in TeX, and #: is "binary representation" in J. And "rem" is defined in the Haskell Standard Prelude. So it's what you're used to, I guess :-)
Why didn't they call it mod(ulus) instead of rem(inder)...
I used remainder at primary school. It wasn't until I started programming I found out the technical term (modulus).
Well, modulus and remainder are different things, when negative numbers are involved. For what it's worth, Haskell defines both. In fact, it has div (divide), quot (quotient), mod (modulus), and rem (remainder). div/mod are a pair, and quot/rem are another pair.
That's *so* Haskell ;)
Funny, I know "rem" from MS DOS batch scripting days :-) I always thought it was short for "remove", ha ha ha!
Post a Comment