cybersecurity · intermediate · ~20 min

Base64 encode

Implement standard Base64 encoding (3 bytes -> 4 chars with '=' padding).

Challenge

Implement int b64_encode(const unsigned char *in, size_t n, char *out) that Base64-encodes n bytes from in into the NUL-terminated string out (RFC 4648 standard alphabet, = padding) and returns the encoded length (excluding the NUL). out is large enough.

Base64 is encoding, not encryption — anyone can reverse it. This is the encoder counterpart to the existing decode exercise.

Starter code

#include <stddef.h>

int b64_encode(const unsigned char *in, size_t n, char *out) {
    /* TODO: encode 3 bytes -> 4 chars, pad with '='. NUL-terminate.
       Return the number of chars written (excluding the NUL). */
    (void)in; (void)n; out[0] = '\0'; return 0;
}

Common mistakes

Forgetting padding for partial groups; sign-extending bytes (cast to unsigned); not NUL-terminating.

Edge cases to handle

Empty input (length 0). 1- and 2-byte tails (one/two '=').

Complexity

O(n).

Background lessons

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.