Monday, August 27, 2007

Erlang Bit Syntax II

Since my previous post on the subject was so lame you should take a look at a better article on the subject.

Saturday, August 11, 2007

Erlang bit syntax

I've been hacking around with Erlang off and on the last few weeks because I think it will be immediately useful for a few problems I'd like to solve. When people are first exposed to Erlang they are often impressed by its support for massive concurrency and crazy "assign once" variables. Aside from that I've found Erlang's bit syntax to be a pleasant surprise.

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

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,
DestIP:32, RestDgram/binary>> when HLen >= 5, 4*HLen =< DgramSize ->
OptsLen = 4*(HLen - ?IP_MIN_HDR_LEN),
<<Opts:OptsLen/binary,Data/binary>> = RestDgram,

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.


my google reader feed