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" uDec

To run this program, you’ll need to install the base64 package. You can do this using OPAM:

$ opam install base64

Then, save the code to a file (e.g., base64_encoding.ml) and compile it:

$ ocamlc -o base64_encoding base64.cma base64_encoding.ml

Now 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:

  1. We use the base64 library, which provides functions for both standard and URL-safe base64 encoding and decoding.

  2. The B64.encode and B64.decode functions are used for standard base64 encoding and decoding.

  3. The B64.encode_url and B64.decode_url functions are used for URL-safe base64 encoding and decoding.

  4. We use try ... with to handle potential decoding errors, as the decode functions can raise an Invalid_argument exception for invalid input.

  5. OCaml’s Printf.printf function is used for output, similar to Go’s fmt.Println.

This example demonstrates how to perform base64 encoding and decoding in OCaml, providing functionality similar to the original Go example.