Base64 Encoding in OCaml
Here’s the translation of the Base64 Encoding example from Go to OCaml:
Our program demonstrates base64 encoding and decoding in OCaml. Here’s the full source code:
To run this program, you’ll need to install the base64
package. You can do this using OPAM:
Then, save the code to a file (e.g., base64_encoding.ml
) and compile it:
Now you can run the program:
The string encodes to slightly different values with the standard and URL-safe base64 encoders (trailing +
vs -
) but they both decode to the original string as desired.
In this OCaml version:
We use the
base64
library, which provides functions for both standard and URL-safe base64 encoding and decoding.The
B64.encode
andB64.decode
functions are used for standard base64 encoding and decoding.The
B64.encode_url
andB64.decode_url
functions are used for URL-safe base64 encoding and decoding.We use
try ... with
to handle potential decoding errors, as thedecode
functions can raise anInvalid_argument
exception for invalid input.OCaml’s
Printf.printf
function is used for output, similar to Go’sfmt.Println
.
This example demonstrates how to perform base64 encoding and decoding in OCaml, providing functionality similar to the original Go example.