Base64 Encoding in Pascal

Our first example demonstrates base64 encoding and decoding. Pascal provides support for base64 encoding/decoding through various libraries, but for this example, we’ll use the base64 unit from the Free Pascal Compiler (FPC).

program Base64Example;

{$mode objfpc}{$H+}

uses
  SysUtils, base64;

var
  data, sEnc, sDec, uEnc, uDec: string;

begin
  // Here's the string we'll encode/decode
  data := 'abc123!?$*&()''''-=@~';

  // Standard base64 encoding
  sEnc := EncodeStringBase64(data);
  WriteLn(sEnc);

  // Decoding the standard base64 encoded string
  sDec := DecodeStringBase64(sEnc);
  WriteLn(sDec);
  WriteLn;

  // URL-safe base64 encoding
  uEnc := EncodeStringBase64URL(data);
  WriteLn(uEnc);

  // Decoding the URL-safe base64 encoded string
  uDec := DecodeStringBase64URL(uEnc);
  WriteLn(uDec);
end.

In this Pascal example, we’re using the base64 unit which provides both standard and URL-safe base64 encoding and decoding functions.

The EncodeStringBase64 and DecodeStringBase64 functions handle standard base64 encoding and decoding, while EncodeStringBase64URL and DecodeStringBase64URL handle URL-safe base64 encoding and decoding.

To run the program, save it as base64_example.pas and compile it using the Free Pascal Compiler:

$ fpc base64_example.pas
$ ./base64_example

The output will be similar to:

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

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

Note that the standard and URL-safe base64 encodings differ slightly (trailing + vs -), but both decode to the original string as expected.

In Pascal, error handling for these functions is typically done through exceptions, so you might want to wrap the decoding operations in a try-except block if you’re unsure about the input format.