cybersecurity · intermediate · ~20 min

Base64 encode

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

Challenge

Encode raw bytes as standard Base64 — the encoder counterpart to decoding, used everywhere security tooling moves binary through text.

Task

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).

Input

  • in: a byte buffer the grader passes.
  • n: the number of bytes to encode.
  • out: caller buffer, guaranteed large enough for the result plus NUL.

Output

Writes the encoded string into out, NUL-terminates it, and returns the number of characters written (excluding the NUL).

Example

b64_encode("foo", 3, out)     ->   4,  out = "Zm9v"
b64_encode("fo", 2, out)      ->   4,  out = "Zm8="
b64_encode("f", 1, out)       ->   4,  out = "Zg=="
b64_encode("foobar", 6, out)  ->   8,  out = "Zm9vYmFy"
b64_encode("", 0, out)        ->   0,  out = ""

Edge cases

  • Empty input writes an empty string and returns 0.
  • A 1-byte tail produces 2 chars + ==; a 2-byte tail produces 3 chars + =.
  • Cast each byte to unsigned before shifting to avoid sign extension.

Rules

  • This is encoding, not encryption — anyone can reverse it.

Input format

A byte buffer in, its length n, and an output buffer out (large enough).

Output format

An int: the number of encoded chars written (excluding the NUL); out is NUL-terminated.

Constraints

RFC 4648 standard alphabet with = padding; NUL-terminate out.

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.