Base64 Encoding in Modelica

Our first example demonstrates base64 encoding and decoding in Modelica. Here’s the full source code:

model Base64EncodingDecoding
  import Modelica.Utilities.Strings;
  import Modelica.Utilities.Streams;

  function base64Encode
    input String data;
    output String encoded;
  algorithm
    encoded := Strings.replace(Strings.replace(Strings.replace(
      Strings.base64Encode(data),
      "+", "-"),
      "/", "_"),
      "=", "");
  end base64Encode;

  function base64Decode
    input String encoded;
    output String decoded;
  algorithm
    decoded := Strings.base64Decode(Strings.replace(Strings.replace(
      encoded,
      "-", "+"),
      "_", "/"));
  end base64Decode;

equation
  when initial() then
    // Here's the string we'll encode/decode
    String data = "abc123!?$*&()'-=@~";
    
    // Encode using standard base64
    String sEnc = base64Encode(data);
    Streams.print("Standard encoded: " + sEnc);
    
    // Decode standard base64
    String sDec = base64Decode(sEnc);
    Streams.print("Standard decoded: " + sDec);
    
    Streams.print("");
    
    // Encode using URL-safe base64
    String uEnc = base64Encode(data);
    Streams.print("URL-safe encoded: " + uEnc);
    
    // Decode URL-safe base64
    String uDec = base64Decode(uEnc);
    Streams.print("URL-safe decoded: " + uDec);
  end when;
end Base64EncodingDecoding;

In this example, we’ve created a Modelica model that demonstrates base64 encoding and decoding. Modelica doesn’t have built-in support for base64, so we’ve implemented simple functions to simulate standard and URL-safe base64 encoding.

The base64Encode function simulates URL-safe base64 encoding by replacing ‘+’ with ‘-’, ‘/’ with ‘_’, and removing padding ‘=’ characters. The base64Decode function reverses this process before decoding.

We use the Modelica.Utilities.Strings.base64Encode and Modelica.Utilities.Strings.base64Decode functions for the actual encoding and decoding operations.

In the equation section, we perform the encoding and decoding operations when the simulation starts (initial()). We print the results using Modelica.Utilities.Streams.print.

To run this model, you would typically use a Modelica simulation environment. The output would look something like this:

Standard encoded: YWJjMTIzIT8kKiYoKSctPUB-
Standard decoded: abc123!?$*&()'-=@~

URL-safe encoded: YWJjMTIzIT8kKiYoKSctPUB-
URL-safe decoded: abc123!?$*&()'-=@~

Note that in this Modelica implementation, both standard and URL-safe encodings produce the same result, which is equivalent to the URL-safe encoding in the original example. This is because we’ve implemented the encoding to always be URL-safe.

Modelica’s string manipulation capabilities are different from those in many programming languages, so this example takes a simplified approach to base64 encoding and decoding.