Decoding Binary Messages

Problem

You have a string containing the characters 0 and 1, representing, in binary, the ASCII values of some text. You want to convert this string into normal, readable, ASCII.

Solution

This would probably be an appropriate place to demonstrate some of Erlang's built-in support for communicating with remote systems, converting text into binary format, and so forth. But, we will save those topics for their own recipes. This topic will be treated as was done in the original Schematics Cookbook.

The solution has three steps:

Chop the string into its component parts. ASCII values are 8 bits long, so we chop the string into sub-strings that are 8 characters long
Convert each substring into the number it represents. Luckily for us Erlangers, this is equivalent to the character value, and can be treated as such.
Combine all the ASCII characters into a single string

The Erlang system comes with io_lib functions to convert from strings to numbers (via io_lib:fread) and vice-versa (via io_lib:format). For example:

1> io_lib:fread("~d", "100").
{ok,"d",[]}
% Note: The "d" is just an aspect of Erlang's odd handling of
% strings as lists of decimal numbers. The ASCII value of the
% character "d" is 100:
2> $d.
100
3> io_lib:format("~B", 100).
["100"]

Both procedures take an additional (optional) argument, which specifies the radix ("base") to use. The default is 10, but values of 2 through 36 may also be used. In the recipe above the radix 2 (format of "~2u") specifies that we are converting to numbers from a base 2 representation. If, for example, the numbers were represented in base 16 (hexadecimal) it would be a simple matter to replace bin_string_to_integer with the procedure: