Base64 Encoding in Nim
Our first example demonstrates base64 encoding and decoding in Nim. Here’s the full source code:
Nim provides built-in support for base64 encoding/decoding through the base64
module.
In this example, we first import the necessary modules: base64
for encoding and decoding, and strutils
for string manipulation (although we don’t explicitly use it in this example, it’s often useful in conjunction with base64 operations).
We define a main
procedure to encapsulate our code. Inside main
, we first define our test string data
.
For standard base64 encoding, we use the encode
function from the base64
module. The decode
function is used for decoding. Note that in Nim, decoding can raise an exception if the input is not valid base64, so we wrap it in a try-except block.
For URL-safe base64 encoding and decoding, we use the same encode
and decode
functions, but we pass the safe = true
parameter to use the URL-safe alphabet.
Finally, we call the main
procedure to execute our code.
To run the program, save it as base64_encoding.nim
and use the Nim compiler:
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.