What would someone want to do with a bunch of nasty bits? Well the example in the PragProg book shows how to create a SHOUTcast server for streaming MP3s. Using the bit syntax you can elegantly chop up the binary blobs to read the metadata.
Here's an (unrelated) example taken from erlange.se:
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,
...
end.
I appologize for the lack of indentation. The method I have used previously for escaping code didn't like Erlang's use of '<<' instead of blogger's PRE tag. It's that specific syntax, however, that is used for Erlang's bit packing and unpacking. Equivalent code written in most languages would get a little nasty. If you would like to see documentation on the syntax be sure to check out this site.
No comments:
Post a Comment