stlencoders

Generic Base2/16/32/64 Encoding Algorithms for C++

stlencoders is a C++ implementation of the Base16, Base32 and Base64 encoding schemes as defined in RFC 4648. Base2, i.e. binary encoding, is also supported.

In a nutshell, the stlencoders library

Examples

A simple program that Base64-encodes standard input to standard output can be essentially written as:

#include <stlencoders/base64.hpp>

#include <iostream>
#include <iterator>

int main()
{
    std::istreambuf_iterator<char> in(std::cin);
    std::istreambuf_iterator<char> end;
    std::ostreambuf_iterator<char> out(std::cout);

    stlencoders::base64<char>::encode(in, end, out);

    return 0;
}

To produce MIME-compliant output, i.e. limit the line length of encoded data to 76 characters with CRLF as line delimiter, use an output iterator adaptor such as stlencoders::line_wrapper:

stlencoders::base64<char>::encode(in, end, stlencoders::line_wrapper(out, 76, "\r\n"));

To use a different encoding alphabet, such as the base64url scheme, which uses the characters '-' and '_' instead of '+' and '/', provide an appropriate traits class:

stlencoders::base64<char, stlencoders::base64url_traits<char> >::encode(in, end, out);

When decoding, a predicate can be specified to indicate which non-alphabet characters should be ignored. To skip all whitespace in a locale-aware manner, one can use

stlencoders::base64<char>::decode(in, end, out, std::bind(std::isspace<char>, _1, std::locale()));

Of course, stlencoders can work with other container types, too. Even wide-character strings are supported:

std::wstring s(L"Zm9vYmFy");
std::vector<std::uint8_t> v;

stlencoders::base64<wchar_t>::decode(s.begin(), s.end(), std::back_inserter(v));

Credits

stlencoders was inspired by Nick Galbreath's excellent stringencoders library. If you strive for maximum performance, or happen to code in plain C, check it out!