F# – Imitating Erlang’s bit syntax for easier binary protocol implementation

Bit Syntax in Erlang

One of the often under-appre­ci­at­ed fea­tures of Erlang is its Bit Syn­tax for pars­ing and pat­tern match­ing bina­ry data at a bit lev­el. For instance, to pare TCP seg­ments you can write some­thing along the line of:



The same capa­bil­i­ty can be applied to any­thing bina­ry pro­to­cols, such as video encod­ing, imag­ing, or UDP.


Imitating with F# Computation Expressions



Whilst this capa­bil­i­ty is not built into F#, or any oth­er lan­guage that I know of for that mat­ter, we do have a very pow­er­ful, and robust fea­ture in F# in Com­pu­ta­tion Expres­sions.

With com­pu­ta­tion expres­sions, I was able to cre­ate a small library that allows you to write and read data to and from a stream at a bit lev­el. With the bitWriter and bitRead­er work­flows you will be able to write and parse TCP head­ers with code like the fol­low­ing:


The library is avail­able via Nuget:

please give it a try, and let me know if you find any bugs here.


p.s. there is still much work to be done on the library. For instance, it’s allo­cat­ing a new buffer array for each work­flow rather than using a buffer pool. If you find this library use­ful and in need for greater per­for­mance, please feel free to con­tribute and help improve the per­for­mance of this library.