Base64 Encoding in Lisp
Here’s the translation of the Base64 Encoding example from Go to Lisp, formatted in Markdown suitable for Hugo:
(defpackage :base64-encoding
(:use :cl))
(in-package :base64-encoding)
;; We'll use the cl-base64 library for base64 encoding/decoding
(ql:quickload :cl-base64)
(defun main ()
;; Here's the string we'll encode/decode
(let ((data "abc123!?$*&()'-=@~"))
;; Standard base64 encoding
(let ((sEnc (cl-base64:string-to-base64-string data)))
(format t "~A~%" sEnc)
;; Decoding
(let ((sDec (cl-base64:base64-string-to-string sEnc)))
(format t "~A~%~%" sDec)))
;; URL-safe base64 encoding
(let ((uEnc (cl-base64:string-to-base64-string data :uri t)))
(format t "~A~%" uEnc)
;; Decoding URL-safe base64
(let ((uDec (cl-base64:base64-string-to-string uEnc :uri t)))
(format t "~A~%" uDec)))))
(main)
Common Lisp provides base64 encoding/decoding through third-party libraries. In this example, we’re using the cl-base64
library.
First, we define a package and load the cl-base64
library using Quicklisp, a library manager for Common Lisp.
In the main
function:
We define the string we’ll encode and decode.
For standard base64 encoding, we use
cl-base64:string-to-base64-string
. This function takes a string and returns its base64 encoded version.To decode, we use
cl-base64:base64-string-to-string
, which takes a base64 encoded string and returns the original string.For URL-safe base64 encoding, we use the same functions but with the
:uri t
keyword argument. This ensures that the encoding is safe for use in URLs.We print the results of each operation using
format
.
To run this program, save it to a file (e.g., base64-encoding.lisp
), ensure you have Quicklisp installed and configured, then run it using your Common Lisp implementation. For example, with SBCL:
$ sbcl --load base64-encoding.lisp
The output will be similar to:
YWJjMTIzIT8kKiYoKSctPUB+
abc123!?$*&()'-=@~
YWJjMTIzIT8kKiYoKSctPUB-
abc123!?$*&()'-=@~
Note that the standard and URL-safe encodings differ slightly (trailing +
vs -
), but they both decode to the original string as expected.