Bitstrings and Binaries (Erlang bit syntax minihowto part 2)

What’s the difference between the Binary and Bitstring types in Erlang? Well, a bitstring is a sequence of bits of any length; a binary is a sequence of bits where the number of bits is evenly divisible by 8. (So any binary is also a bitstring.)

Some examples:

1> <<2#11110000:5>>.
2> <<2#11110000:6>>.
3> erlang:is_bitstring(<<2#11110000:6>>).
4> erlang:is_binary(<<2#11110000:6>>).
5> erlang:is_bitstring(<<2#11110000:8>>).
6> erlang:is_binary(<<2#11110000:8>>).

In the Erlang bit syntax there are 2 clarifying (?) type synonyms:

bytes == binary
bits  == bitstring

which are basically telling you to think of binaries as sequence of bytes, and bitstrings as sequence of bits. Quite obvious right? Well, it wasn’t for me at first.

It’s also worth noting how binaries and bitstrings are converted into text strings. Given the binary <<16#50>> storing the letter ‘P’,

7> <<16#50>>
8>erlang:bitstring_to_list(<<16#50>>). #I could've used binary_to_list()
"P"          %great!
[<<16:5>>]  %mmh...

The result of command #9 is not exactly what I had imagined. Yes, it’s a list, but it’s certainly not a text string, and I was expecting a text string. Why was I expecting a text string if the API is named bitstring_to_list() ? Because if I was in the middle of coding a text manipulation algorithm and called bitstring_to_list(), I would probably (wrongly) assume that it would do some magic and transform any bitstring in a usable text string. Why? Because we are used to treat text strings as lists. Why? Because we don’t have APIs that mention “strings”: all the builtin APIs only mention lists. That’s the problem. We are using a list API as if it was a string API, when a generic list is not necessarily a string.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s