</>EmbeddedInterview

How do you align a value up or down to a power-of-two boundary?

EasyBit Manipulation

Short answer: Align down with x & ~(a - 1); align up with (x + a - 1) & ~(a - 1). Both require a to be a power of two.

#define ALIGN_DOWN(x, a)  ((x) & ~((a) - 1))
#define ALIGN_UP(x, a)    (((x) + (a) - 1) & ~((a) - 1))
#define IS_ALIGNED(x, a)  (((x) & ((a) - 1)) == 0)

Examples with a = 8 (mask ~7 = ...11111000)

x ALIGN_DOWN ALIGN_UP
13 8 16
16 16 16
1 0 8

Why it works: a - 1 is a mask of the low bits (7 = 0b111). Clearing them rounds down to a multiple of a. Adding a - 1 first pushes any value that is not already aligned past the next boundary, so the clear then rounds up.

Where you use it in embedded work

  • DMA buffers and caches: on a Cortex-M7 with D-cache, a DMA buffer should start and end on a 32-byte cache-line boundary so that cache clean/invalidate does not touch neighbouring variables.
  • Memory allocators: returning 8-byte aligned blocks so double and uint64_t work.
  • Page arithmetic: ALIGN_DOWN(addr, 4096) gives the page base address.
  • Stack pointers: the AAPCS requires 8-byte stack alignment at public function calls.

Pitfalls

  • With a pointer, cast to uintptr_t first: ALIGN_UP((uintptr_t)p, 32).
  • Types must match: if x is 64-bit and a is an unsigned int, ~(a - 1) is a 32-bit mask and clears the upper 32 bits of x. Cast a to the type of x.
  • ALIGN_UP can overflow near the top of the address range.

For non-power-of-two alignment, use ((x + a - 1) / a) * a.