Base64 Encoding in D Programming Language

Our first example demonstrates base64 encoding and decoding in D. D provides built-in support for base64 encoding/decoding.

import std.base64;
import std.stdio;

void main()
{
    // Here's the string we'll encode/decode.
    string data = "abc123!?$*&()'-=@~";

    // D supports both standard and URL-compatible base64.
    // Here's how to encode using the standard encoder.
    string sEnc = Base64.encode(cast(ubyte[])data);
    writeln(sEnc);

    // Decoding may return an error, which you can check
    // if you don't already know the input to be well-formed.
    ubyte[] sDec = Base64.decode(sEnc);
    writeln(cast(string)sDec);
    writeln();

    // This encodes/decodes using a URL-compatible base64 format.
    string uEnc = Base64URL.encode(cast(ubyte[])data);
    writeln(uEnc);
    ubyte[] uDec = Base64URL.decode(uEnc);
    writeln(cast(string)uDec);
}

In this D code, we use the std.base64 module which provides both standard and URL-compatible base64 encoding and decoding.

To run the program, save it as base64_encoding.d and use the D compiler:

$ dmd -run base64_encoding.d
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.

In D, we use Base64.encode and Base64.decode for standard base64 encoding and decoding, and Base64URL.encode and Base64URL.decode for URL-compatible base64 encoding and decoding. The cast keyword is used to convert between string and ubyte[] types as required by the encoding and decoding functions.