Skip to content

Instantly share code, notes, and snippets.

@TheWeirdDev
Last active July 6, 2020 14:33
Show Gist options
  • Save TheWeirdDev/a0965dddfc240aa64e892d33c2e5a85d to your computer and use it in GitHub Desktop.
Save TheWeirdDev/a0965dddfc240aa64e892d33c2e5a85d to your computer and use it in GitHub Desktop.
Base64 Encode Implementation in D
module mybase64;
import std.stdio;
import std.conv;
import std.array;
immutable mapping = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
int main() {
auto input = stdin.readln();
string s;
while ((s = stdin.readln()) !is null) {
input ~= s;
}
base64encode(input).writeln;
return 0;
}
string base64encode(in string input) {
ulong len = input.length;
char[] buf;
buf.reserve(31);
while(len >= 3) {
buf ~= mapping[input[$-len] >> 2];
buf ~= mapping[((input[$-len] & 0x3) << 4) | (input[$-len+1] & 0xf0) >> 4];
buf ~= mapping[((input[$-len+1] & 0x0f) << 2) | input[$-len+2] >> 6];
buf ~= mapping[input[$-len+2] & 0x3f];
len -= 3;
}
if (len == 2) {
buf ~= mapping[input[$-len] >> 2];
buf ~= mapping[((input[$-len] & 0x3) << 4) | (input[$-len+1] & 0xf0) >> 4];
buf ~= mapping[(input[$-len+1] & 0x0f) << 2];
buf ~= "=";
} else if (len == 1) {
buf ~= mapping[input[$-len] >> 2];
buf ~= mapping[(input[$-len] & 0x3) << 4];
buf ~= "==";
}
return buf.to!string;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment