Home > Articles > Programming > General Programming/Other Languages

  • Print
  • + Share This
Like this article? We recommend

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:


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:


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:


On top of this, the bit syntax supports pattern matching, so you can use partially instantiated binary objects in function definitions and case statements.

  • + Share This
  • 🔖 Save To Your Account