How to align a value to a given alignment
If the alignment is a power of 2, and the machine uses complement of 2 for negative numbers then:
mask = alignment - 1;
aligned_val = unaligned_val + (-unaligned_val & mask);
Lets say alignment is a
---(k-1)a-----------x--------------ka---------
<----r----><-----(a-r)--->
where k
is an integer (so ka
is a multiple of alignment)
First find the remainder
r = x%a
then increment x to next multiple
y = x + (a-r)
But if r = 0, then y = x
So finally
r = x%a;
y = r? x + (a - r) : x;