Skip to content

Instantly share code, notes, and snippets.

@cls
Last active January 23, 2020 07:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save cls/4f141edf394f7abf85e7e5c1a450368d to your computer and use it in GitHub Desktop.
Save cls/4f141edf394f7abf85e7e5c1a450368d to your computer and use it in GitHub Desktop.
Straightforward constexpr Base64 block encoding in C++14
#include <array>
#include <tuple>
constexpr std::array<char, 4> base64(uint8_t octet0, uint8_t octet1, uint8_t octet2)
{
constexpr std::array<char, 64> table = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z', '0', '1', '2', '3',
'4', '5', '6', '7', '8', '9', '+', '/',
};
const uint_fast32_t value = (octet0 << (2 * 8))
| (octet1 << (1 * 8))
| (octet2 << (0 * 8));
const char hexad0 = table[(value >> (3 * 6)) % table.size()];
const char hexad1 = table[(value >> (2 * 6)) % table.size()];
const char hexad2 = table[(value >> (1 * 6)) % table.size()];
const char hexad3 = table[(value >> (0 * 6)) % table.size()];
return {hexad0, hexad1, hexad2, hexad3};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment