Skip to content

Instantly share code, notes, and snippets.

@artemklevtsov
Last active September 3, 2019 02:05
Show Gist options
  • Save artemklevtsov/78c9955c0b583e56b40ebfce56c77455 to your computer and use it in GitHub Desktop.
Save artemklevtsov/78c9955c0b583e56b40ebfce56c77455 to your computer and use it in GitHub Desktop.
#include <Rcpp.h>
using namespace Rcpp;
constexpr auto b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
// [[Rcpp::export]]
std::string base64_encode(const RawVector& input) {
std::string out;
out.reserve(input.size() / 3 * 4 + 4);
int remainder = 0;
unsigned char leftover = 0;
for (unsigned char c: input) {
remainder %= 3; // which byte of 3-bytes sequence
switch (remainder) {
case 0: // 1 byte of 3
out += b64[c >> 2];
leftover = c << 6; // last 2 bits
break;
case 1: // 2 byte of 3
out += b64[(leftover >> 2) + (c >> 4)];
leftover = c << 4;
break;
case 2: // 3 by of 3
out += b64[(leftover >> 2) + (c >> 6)];
out += b64[c & 0x3F];
break;
}
remainder++;
}
switch (remainder) {
case 1:
out += b64[leftover >> 2];
out += "==";
break;
case 2:
out += b64[leftover >> 2];
out += "=";
break;
}
return out;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment