Base64 Encoding in Erlang

Our example demonstrates base64 encoding and decoding in Erlang. Erlang provides built-in support for base64 encoding/decoding through the base64 module.

-module(base64_encoding).
-export([main/0]).

main() ->
    % Here's the string we'll encode/decode
    Data = "abc123!?$*&()'-=@~",

    % Erlang supports both standard and URL-compatible base64
    % Here's how to encode using the standard encoder
    SEnc = base64:encode(Data),
    io:format("~s~n", [SEnc]),

    % Decoding may return an error, which you can check
    % if you don't already know the input to be well-formed
    {ok, SDec} = base64:decode(SEnc),
    io:format("~s~n~n", [SDec]),

    % This encodes/decodes using a URL-compatible base64 format
    UEnc = base64:encode_to_string(Data),
    io:format("~s~n", [UEnc]),
    {ok, UDec} = base64:decode(UEnc),
    io:format("~s~n", [UDec]).

In Erlang, we use the base64 module for encoding and decoding. The encode/1 function is used for standard base64 encoding, while encode_to_string/1 is used for URL-compatible encoding. Both functions return a string.

For decoding, we use the decode/1 function, which returns a tuple {ok, DecodedBinary} on success or {error, Reason} on failure. We’re using pattern matching to extract the decoded binary.

To run the program, save it as base64_encoding.erl and use the Erlang shell:

$ erl
1> c(base64_encoding).
{ok,base64_encoding}
2> base64_encoding:main().
YWJjMTIzIT8kKiYoKSctPUB+
abc123!?$*&()'-=@~

YWJjMTIzIT8kKiYoKSctPUB+
abc123!?$*&()'-=@~

The string encodes to the same value with both the standard and URL-compatible base64 encoders in Erlang, and they both decode to the original string as desired.

Note that in Erlang, strings are represented as lists of integers, and the base64 functions work with binaries. The conversion between these types is handled automatically in this example for simplicity.