The Bit Syntax
One of my favorite parts of the language is the bit syntax. Erlang supports a binary type, which can contain any binary data. This arrangement is very useful when writing network code, because any range of bits can be accessed easily. The bit syntax calls for a list of numbers in double angle brackets. The following example is three bytes long, with the bytes set to 1, 2, and 3, respectively:
<<1,2,3>>
By itself, this isn’t very useful; it’s little more than an array of 8-bit values, after all. Each of these values can have a length specifier appended, however, telling Erlang how much space to take up with the values. The following two representations are equivalent on a big-endian architecture:
<<1:32,2,3>> <<0,0,0,1,2,3>>
Remember that I said "on a big-endian architecture." That’s important. If we’re dealing with network code, we’re likely to want to swap things between network and host byte order. Pulling data off a TCP connection and onto an x86 machine will require that the data be converted from big-endian to little-endian format. On Erlang, the following two forms are equivalent:
<<1:32/little,2,3>> <<1,0,0,0,2,3>>
On top of this, the bit syntax supports pattern matching, so you can use partially instantiated binary objects in function definitions and case statements.