All codecs in cppcodec (e.g., base64, base32, hex) provide several ways to encode binary data into an encoded string.
Supported Types
For template parameters T (input) and Result (output), you can use types like std::vector<uint8_t> or std::string that support:
.data() and .size() for input types T..reserve(size_t), .resize(size_t), and .push_back([uint8_t|char]) for output types Result.
Encoding Methods
1. Convenient versions (returns a new object)
These return a new instance of the requested type (e.g., std::string or a templated Result).
std::string <codec>::encode(const [uint8_t|char]* binary, size_t binary_size);std::string <codec>::encode(const T& binary);Result <codec>::encode<Result>(const [uint8_t|char]* binary, size_t binary_size);Result <codec>::encode<Result>(const T& binary);
2. Reused container version
Resizes the provided encoded_result container before writing to it. This is useful for avoiding repeated allocations.
void <codec>::encode(Result& encoded_result, const [uint8_t|char]* binary, size_t binary_size);void <codec>::encode(Result& encoded_result, const T& binary);
3. Pre-allocated memory version (noexcept)
Encodes directly into a raw buffer. This version is noexcept but will call abort() if the provided buffer is too small.
size_t <codec>::encode(char* encoded_result, size_t encoded_buffer_size, const [uint8_t|char]* binary, size_t binary_size) noexcept;size_t <codec>::encode(char* encoded_result, size_t encoded_buffer_size, const T& binary) noexcept;
To ensure a null-terminated C string, provide a buffer of size <codec>::encoded_size(binary_size) + 1.
// Example: Encoding to a string
std::string encoded = cppcodec::base64::encode(my_binary_data);
// Example: Encoding into a pre-allocated buffer
size_t required = cppcodec::base64::encoded_size(binary_size);
std::vector<char> buffer(required + 1);
size_t actual_size = cppcodec::base64::encode(buffer.data(), buffer.size(), binary_ptr, binary_size);