cybersecurity · beginner · ~15 min

Base64 encoded length

Compute the padded base64 output size.

Challenge

Compute how many characters the padded base64 encoding of some bytes will take — the size you must allocate before encoding.

Task

Implement int base64_len(int n) that returns the length of the base64 encoding of n input bytes.

Input

  • n: the number of raw input bytes.

Output

Returns int: the padded base64 length, 4 * ceil(n / 3), i.e. 4 * ((n + 2) / 3).

Example

base64_len(3)   ->   4
base64_len(1)   ->   4
base64_len(6)   ->   8
base64_len(0)   ->   0

Edge cases

  • 0 bytes encode to length 0.
  • Each partial final group still costs a full 4 characters (padded with =).

Input format

An int n: the number of raw input bytes.

Output format

An int: the padded base64 length 4 * ((n + 2) / 3).

Constraints

Round each 3-byte group up to 4 characters.

Starter code

int base64_len(int n) {
    /* TODO */
    return 0;
}

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