Topics / Pointers & Memory / Q27
Check memory address alignment for 4, 8, 16, or 64 bytes
A memory address is aligned to N bytes if it is exactly divisible by N. For power-of-two alignments, we can check this without using the modulo operator.
1. Generic formula
is_aligned = !(addr & (alignment - 1));
2. C program
#include <stdio.h>
#include <stdint.h>
int is_aligned(uintptr_t addr, unsigned int alignment)
{
return !(addr & (alignment - 1));
}
int main()
{
uintptr_t addr = 0x1020;
printf("4-byte aligned: %d\n", is_aligned(addr, 4));
printf("8-byte aligned: %d\n", is_aligned(addr, 8));
printf("16-byte aligned: %d\n", is_aligned(addr, 16));
printf("64-byte aligned: %d\n", is_aligned(addr, 64));
return 0;
}
Output:
4-byte aligned: 1
8-byte aligned: 1
16-byte aligned: 1
64-byte aligned: 0
3. How does it work?
For an address to be aligned to a power of two, certain least significant bits must be zero.
| Alignment | Mask | Required zero bits |
|---|---|---|
| 4 bytes | 0x03 | Last 2 bits |
| 8 bytes | 0x07 | Last 3 bits |
| 16 bytes | 0x0F | Last 4 bits |
| 32 bytes | 0x1F | Last 5 bits |
| 64 bytes | 0x3F | Last 6 bits |
For example, checking 16-byte alignment for address 0x1020 (lower eight bits):
Address 00100000
Mask 00001111
AND 00000000
Result is zero — 16-byte aligned.
4. Direct bitwise expressions
is_4_aligned = !(addr & 3);
is_8_aligned = !(addr & 7);
is_16_aligned = !(addr & 15);
is_64_aligned = !(addr & 63);
5. Important interview follow-up
Handle invalid alignment values, such as 0, 3 or 7.
int is_aligned(uintptr_t addr, unsigned int alignment)
{
// Check if alignment is a valid power of 2
if (!alignment || (alignment & (alignment - 1)))
return 0;
return !(addr & (alignment - 1));
}
Time complexity: O(1).
Space complexity: O(1).
Embedded applications: DMA buffer alignment, cache-line alignment, ARM memory access, SIMD instructions and memory allocators.
Remember to use uintptr_t instead of int when converting pointers to integers, especially on 64-bit platforms.