Skip to content
gaspardpetitPublic

About

An efficient C/C++ Base64 encoder and decoder

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

base64

An efficient Base64 encoder and decoder for C and C++, with a portable scalar implementation and optional AVX2 and NEON backends. At a 32 KiB payload size, the SIMD backend ranks first for combined encoding and decoding throughput in the current Windows and Linux results, and second on macOS, from base64-benchmark. The portable path is the fastest architecture-neutral encoder and decoder in the same benchmark results.

Benchmark rankings depend on the processor, compiler, payload size, validation requirements, and calling interface. See the benchmark repository for the source, test conditions, and results for individual operations.

C

Compile base64.c and include the header:

#include "base64.h"

For header-only use, define BASE64_HEADER_ONLY before including the header:

#define BASE64_HEADER_ONLY
#include "base64.h"

Allocate base64_encoded_size(input_size) bytes for encoding or base64_decoded_max_size(input_size) bytes for decoding. The functions return the number of bytes written. base64_decode accepts the standard alphabet, while base64url_decode accepts both the standard and URL-safe alphabets. Both return BASE64_ERROR for invalid input.

Use base64url_encode to produce URL-safe Base64. It has the same buffer-size and return-value contract as base64_encode.

base64_decode_unchecked skips character validation when the input is already trusted. It remains bounds-safe and checks the encoded length and padding, but invalid alphabet characters produce unspecified decoded bytes.

base64_compact removes every byte from 0x00 through ASCII space (0x20), which efficiently strips common control-character and whitespace contamination before decoding. It modifies the supplied buffer in place and returns its new length. A buffer containing no removable bytes is not written.

base64_decode_whitespace composes this operation with checked decoding for a complete in-memory message. It modifies the encoded input buffer in place and returns the decoded size, or BASE64_ERROR when malformed or when invalid non-whitespace characters remain.

size_t decoded_size = base64_decode_whitespace(
    encoded, encoded_size, decoded);

C++

Compile base64.cpp and include the header:

#include "base64.hpp"

std::string encoded = base64::encode("Hello");
std::string url_encoded = base64::url_encode("Hello");
std::string decoded = base64::decode(encoded);

For header-only use, define BASE64_CPP_HEADER_ONLY before including the header:

#define BASE64_CPP_HEADER_ONLY
#include "base64.hpp"

To reuse caller-owned storage:

std::string encoded;
encoded.reserve(base64_encoded_size(input.size()));
base64::encode(input, encoded);

std::string decoded;
decoded.reserve(base64_decoded_max_size(encoded.size()));
if (!base64::decode(encoded, decoded)) {
    // Invalid Base64 input.
}

For trusted input, base64::decode_unchecked provides returning-string and caller-owned-output overloads equivalent to base64::decode.

These overloads do not allocate when the output string already has sufficient capacity. Input and output must be distinct strings.

Command line

The cli directory builds a streaming command compatible with the GNU coreutils base64 interface.

CLI throughput for a 100 MiB payload (decimal GB/s):

Platform Operation This CLI Reference Reference throughput Speedup
Apple M4 Encode 8.098 macOS base64 2.246 3.61x
Apple M4 Decode 5.508 macOS base64 0.076 72.20x
Apple M4 Decode, LF80 (-i) 3.700 macOS base64 0.070 52.59x
Ryzen 7 5700G Encode 6.06 GNU base64 9.4 1.66 3.66x
Ryzen 7 5700G Decode 4.69 GNU base64 9.4 0.67 6.96x
Ryzen 7 5700G Decode, LF80 (-i) 3.20 GNU base64 9.4 0.38 8.46x
Core i9-13900K Encode 2.45 DI / PowerShell 0.27 / 0.16 9.02x / 14.92x
Core i9-13900K Decode 2.10 DI / PowerShell 0.32 / 0.09 6.50x / 24.57x
Core i9-13900K Decode, LF80 (-i) 1.65 DI / PowerShell 0.43 / 0.08 3.82x / 20.03x

Figures are medians from 15 warm-cache whole-process runs, including startup and file I/O, with output discarded. Decoded outputs were verified byte-for-byte. The systems used macOS /usr/bin/base64; Ubuntu 24.04 with Clang 20.1 and AVX2; and Windows 11 with MSVC 19.44 and AVX2. The Windows references were 64-bit DI base64 for Windows 1.3.1 and Windows PowerShell 5.1 with .NET Framework 4.8.

Supported format

base64_encode produces standard padded Base64 as defined by RFC 4648; base64url_encode produces its padded URL-safe variant. base64_decode accepts only the standard (+ and /) alphabet. base64url_decode accepts both the standard and URL-safe (- and _) alphabets, including mixed input. Both decoders accept padded and unpadded input. Whitespace and line-wrapped input are rejected unless the caller first uses base64_compact. Encode and decode input and output buffers must not overlap.

Linux AVX2

Compiled-library builds use runtime AVX2 dispatch on x86-64 with GCC or Clang. Compile the backend separately so the public API and scalar fallback remain usable on processors without AVX2:

clang -O3 -c base64.c
clang -O3 -mavx2 -c base64_avx2.c

Link both objects. CPU detection includes OS support for AVX register state. Define BASE64_DISABLE_HARDWARE when compiling base64.c to omit the backend. Header-only builds remain scalar.

Windows AVX2

Compiled-library builds use runtime AVX2 dispatch by default on Windows x64. Compile base64_avx2.c separately with /arch:AVX2 and link both objects:

cl /O2 /c base64.c
cl /O2 /c /arch:AVX2 base64_avx2.c

For C++, compile base64.cpp instead of base64.c. The public functions detect AVX2 once and otherwise use the portable scalar implementation.

Define BASE64_DISABLE_HARDWARE when compiling base64.c or base64.cpp to build only the portable implementation without linking base64_avx2.c. Header-only builds remain scalar and do not require this definition.

Apple NEON

Compiled-library builds use the NEON backend by default on Apple Silicon and other AArch64 targets. Compile base64_neon.c and link both objects:

clang -O3 -c base64.c
clang -O3 -c base64_neon.c

For C++, compile base64.cpp instead of base64.c. The backend is selected at compile time because NEON is required by AArch64. Define BASE64_DISABLE_HARDWARE when compiling base64.c or base64.cpp to build only the portable implementation without linking base64_neon.c. Header-only builds remain scalar and do not require this definition.

Technical overview

The C API writes directly to caller-provided buffers and performs no dynamic memory allocation. The C++ output overloads resize an existing std::string, allowing callers to reserve and reuse its storage.

Encoding uses a 64 × 64 lookup table that converts 12 input bits into two Base64 characters at once. The main loop processes 12 input bytes per iteration, reducing loop overhead and independent table lookups while remaining portable C.

Decoding uses four position-specific 256-entry tables. Each lookup contributes the decoded bits in their final position, allowing four input characters to be combined with bitwise OR operations while detecting invalid characters. The main loop processes 12 encoded characters at a time and writes the resulting nine bytes with packed stores where the platform permits it.

The optional AVX2 backend processes four 24-byte encoding blocks together. Its main encoding loop uses overlapping 256-bit input loads after an initial safe load, avoiding the cost of assembling each input vector from two smaller loads. The large-input decoder processes four 32-byte blocks per iteration. Decoding uses independently derived hash tables to translate and validate both RFC 4648 alphabets, followed by packed multiply-add operations that assemble the decoded bytes. Checked and unchecked decoding use separately specialized loops. Standard-only decoding uses dedicated mapping and validation tables, while URL-safe-compatible decoding accepts both alphabets in a combined pipeline.

The optional NEON backend processes 48 input bytes per encoding block and 64 Base64 characters per decoding block. Its checked decoder uses compact lookup tables to validate and translate each RFC 4648 alphabet in a dedicated SIMD pipeline. Standard input enters its pipeline directly; a failed standard mapping is retried with the URL-safe pipeline. The unchecked variant skips validation for trusted input and selects its standard or URL-safe pipeline with a one-time alphabet scan.

This project began in 2016, following a post on Stack Overflow. I started tracking variants of Base64 implementations and benchmarking them. It became apparent that not all implementations were equal, and the most efficient ones had to use memory in a very efficient way. This implementation was developed through experiments in the base64-benchmark project and was mostly informed by the table-driven and unrolled approaches used by Chromium's modp_b64 and TurboBase64. The portable path does not require architecture-specific intrinsics.

After many attempts, the 64 × 64 encoding table and four 256-entry decoding tables emerged as the best candidates to outperform existing implementations. The most challenging aspects were around tail management and encoding validation; both can easily consume the bulk of the processing time on small payloads. For architecture-neutral implementations, this decoder and encoder significantly outperform all the best architecture-neutral implementations I could find.

For SIMD, TurboBase64 is really amazing work, and was very difficult to outperform for AVX2 and NEON on the tested systems. I attempted several different approaches which eventually converged to the same strategy and I only managed by a small margin, mostly through careful scheduling and tighter tail handling.

The CLI was based on the GNU interface documented by coreutils, with the GNU tool used as an oracle to ensure compatibility. The overhead for the CLI was mostly load time on small payloads and whitespace handling. Whitespace handling was optimized through an optimistic approach: assume no whitespace and attempt checked decoding first. If it works, we paid no preprocessing cost. With --ignore-garbage, if it fails, common control and whitespace bytes are detected and compacted in bulk: multiple characters in a single register in the architecture-neutral implementation, or through AVX2/NEON vectors when available. Clean chunks avoid unnecessary writes, while remaining invalid characters fall through to the GNU-compatible scalar parser. These optimizations, along with the optimized encoder/decoder, explain the 20-70x decoding speedup compared to the reference implementations.

License

This project is available under the BSD 3-Clause License.

About

An efficient C/C++ Base64 encoder and decoder

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages