Parsing user name and password from binary in Erlang + Cowboy I am working on a web app that uses a WebSocket to log in users. I would like to minimize bandwidth usage by using binary messages. I came up with the following, and would like to know whether there is something better I could be doing:

-define(LOGIN, 1).

websocket_handle({binary, &lt;&lt;?LOGIN:8,LengthUser:8, Rest/bitstring&gt;&gt;}, Req, State) -&gt;
    LU2 = LengthUser*8,
    &lt;&lt;Username:LU2/bitstring, Password/bitstring&gt;&gt; = Rest,
    % Do the actual logging in...


I did a decent amount of research, and couldn't find a way to avoid using the Rest piece in order to accommodate variable length bitstring patterns. The web app uses an ArrayBuffer and a few DataViews in order to construct the message.
Your approach is necessary because of the need to extract the length of the Username field before using it to extract the Username field itself. However, you needn't use bitstring anywhere because you're only sending whole bytes, not bitfields. You can change all occurrences of bitstring to binary instead, and with that change you also no longer need to specify the length of Username in bits, so you no longer need LU2 and can just use LengthUser directly:

-define(LOGIN, 1).

websocket_handle({binary, &lt;&lt;?LOGIN:8,LengthUser:8, Rest/binary&gt;&gt;}, Req, State) -&gt;
    &lt;&lt;Username:LengthUser/binary, Password/binary&gt;&gt; = Rest,
    %% Do the actual logging in...


And finally, note that by convention, Erlang comments on a line by themselves at the current indentation level start with %%, not %. Single % should be used only for end-of-line comments. Not sure about other editors but the emacs erlang-mode indents comments this way, so if an emacs user worked on your code your comments might get wildly indented if the emacs developer auto-indented the buffer and didn't check everything afterwards.