Base64 Encoding in Nim
Our first example demonstrates base64 encoding and decoding in Nim. Here’s the full source code:
import base64, strutils
proc main() =
# Here's the string we'll encode/decode.
let data = "abc123!?$*&()'-=@~"
# Nim provides support for both standard and URL-compatible
# base64. Here's how to encode using the standard encoder.
let sEnc = encode(data)
echo sEnc
# Decoding may raise an exception, which you can catch
# if you don't already know the input to be well-formed.
try:
let sDec = decode(sEnc)
echo sDec
except:
echo "Decoding failed"
echo ""
# This encodes/decodes using a URL-compatible base64 format.
let uEnc = encode(data, safe = true)
echo uEnc
try:
let uDec = decode(uEnc, safe = true)
echo uDec
except:
echo "Decoding failed"
main()
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:
$ nim c -r base64_encoding.nim
YWJjMTIzIT8kKiYoKSctPUB+
abc123!?$*&()'-=@~
YWJjMTIzIT8kKiYoKSctPUB-
abc123!?$*&()'-=@~
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.