basics · intermediate · ~15 min

Align up to a boundary

Round a value up to a power-of-two multiple.

Challenge

Implement:

unsigned align_up(unsigned x, unsigned a);

Return x rounded up to the next multiple of a, where a is a power of two.

Input format

x and a power-of-two alignment a.

Output format

x rounded up to a multiple of a.

Constraints

Already-aligned x is unchanged; a==1 returns x.

Starter code

#include <stddef.h>
/* Round x up to the next multiple of a, where a is a power of two. */
unsigned align_up(unsigned x,unsigned a){ (void)a; return x; }

Common mistakes

Using modulo/division instead of the mask trick; assuming a is arbitrary (it must be a power of two).

Edge cases to handle

4097 aligned to 4096 -> 8192.

Background lessons

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