basics · intermediate · ~15 min
Round a value up to a power-of-two multiple.
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.
x and a power-of-two alignment a.
x rounded up to a multiple of a.
Already-aligned x is unchanged; a==1 returns x.
#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; }
Using modulo/division instead of the mask trick; assuming a is arbitrary (it must be a power of two).
4097 aligned to 4096 -> 8192.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.