cybersecurity · intermediate · ~20 min
Implement standard Base64 encoding (3 bytes -> 4 chars with '=' padding).
Encode raw bytes as standard Base64 — the encoder counterpart to decoding, used everywhere security tooling moves binary through text.
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).
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.Writes the encoded string into out, NUL-terminates it, and returns the number of characters written (excluding the NUL).
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 = ""
==; a 2-byte tail produces 3 chars + =.A byte buffer in, its length n, and an output buffer out (large enough).
An int: the number of encoded chars written (excluding the NUL); out is NUL-terminated.
RFC 4648 standard alphabet with = padding; NUL-terminate out.
#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;
}
Forgetting padding for partial groups; sign-extending bytes (cast to unsigned); not NUL-terminating.
Empty input (length 0). 1- and 2-byte tails (one/two '=').
O(n).
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.