-
-
Save tarhan/c0eb86370253201dd31cd54d82277755 to your computer and use it in GitHub Desktop.
Straightforward constexpr Base64 block encoding in C++14
This file contains 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
#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