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:
open Base64
let () =
(* Here's the string we'll encode/decode. *)
let data = "abc123!?$*&()'-=@~" in
(* OCaml provides standard base64 encoding/decoding. *)
let sEnc = B64.encode data in
Printf.printf "%s\n" sEnc;
(* Decoding may raise an exception, which you can catch
if you don't already know the input to be well-formed. *)
let sDec =
try
B64.decode sEnc
with
| Invalid_argument _ -> "Decoding failed"
in
Printf.printf "%s\n\n" sDec;
(* OCaml also provides URL-safe base64 encoding/decoding. *)
let uEnc = B64.encode_url data in
Printf.printf "%s\n" uEnc;
let uDec =
try
B64.decode_url uEnc
with
| Invalid_argument _ -> "Decoding failed"
in
Printf.printf "%s\n" uDecTo run this program, you’ll need to install the base64 package. You can do this using OPAM:
$ opam install base64Then, save the code to a file (e.g., base64_encoding.ml) and compile it:
$ ocamlc -o base64_encoding base64.cma base64_encoding.mlNow you can run the program:
$ ./base64_encoding
YWJjMTIzIT8kKiYoKSctPUB+
abc123!?$*&()'-=@~
YWJjMTIzIT8kKiYoKSctPUB-
abc123!?$*&()'-=@~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
base64library, which provides functions for both standard and URL-safe base64 encoding and decoding.The
B64.encodeandB64.decodefunctions are used for standard base64 encoding and decoding.The
B64.encode_urlandB64.decode_urlfunctions are used for URL-safe base64 encoding and decoding.We use
try ... withto handle potential decoding errors, as thedecodefunctions can raise anInvalid_argumentexception for invalid input.OCaml’s
Printf.printffunction 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.