Skip to content

Instantly share code, notes, and snippets.

@cls cls/base64.hpp
Last active Feb 13, 2019

Embed
What would you like to do?
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
You can’t perform that action at this time.