Simvik

Align an address

Round an address up to a power-of-two boundary. A medium embedded C problem (Pointers), run and graded in the browser.

medium · Pointers · alignment · masks

Allocators and DMA buffers need addresses that are multiples of 4, 8 or more.

Return addr rounded up to the next multiple of align. align is always a power of two. An address that is already aligned is returned unchanged. Use masking, not division.

Starter code

uint32_t align_up(uint32_t addr, uint32_t align) {
  // Next multiple of align at or above addr.
  return addr;
}

Example tests

Needs rounding

printf("0x%X\n", align_up(0x1001, 4));

Expected output:

0x1004

Already aligned

printf("0x%X\n", align_up(0x1000, 4));

Expected output:

0x1000

Learn it first

  • Pointers · Addresses, arithmetic, const, void pointers and object lifetime.

More Pointers problems