Last active
July 6, 2020 14:33
-
-
Save TheWeirdDev/a0965dddfc240aa64e892d33c2e5a85d to your computer and use it in GitHub Desktop.
Base64 Encode Implementation in D
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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