Base64 Encoding in Prolog

Our program demonstrates base64 encoding and decoding in Prolog. Here’s the full source code:

:- use_module(library(base64)).

main :-
    % Here's the string we'll encode/decode
    Data = "abc123!?$*&()'-=@~",
    
    % Prolog supports both standard and URL-compatible base64
    % Here's how to encode using the standard encoder
    base64(Data, StandardEncoded),
    format('Standard Encoded: ~w~n', [StandardEncoded]),
    
    % Decoding may return an error, which you can check
    % if you don't already know the input to be well-formed
    base64(StandardDecoded, StandardEncoded),
    format('Standard Decoded: ~w~n~n', [StandardDecoded]),
    
    % This encodes/decodes using a URL-compatible base64 format
    base64(Data, URLEncoded, [url(true)]),
    format('URL Encoded: ~w~n', [URLEncoded]),
    base64(URLDecoded, URLEncoded, [url(true)]),
    format('URL Decoded: ~w~n', [URLDecoded]).

:- main.

To run the program, save it as base64_encoding.pl and use the Prolog interpreter:

$ swipl -s base64_encoding.pl
Standard Encoded: YWJjMTIzIT8kKiYoKSctPUB+
Standard Decoded: abc123!?$*&()'-=@~

URL Encoded: YWJjMTIzIT8kKiYoKSctPUB-
URL Decoded: abc123!?$*&()'-=@~

In this Prolog implementation:

  1. We use the base64 library, which provides base64 encoding and decoding functionality.

  2. The base64/2 predicate is used for standard base64 encoding and decoding. The first argument is the input, and the second is the output.

  3. For URL-safe base64 encoding and decoding, we use base64/3 with the url(true) option.

  4. The format/2 predicate is used to print the results.

  5. The :- main. directive at the end ensures that the main/0 predicate is called when the program is run.

The string encodes to slightly different values with the standard and URL base64 encoders (trailing + vs -) but they both decode to the original string as desired.