I have a value that I want to align to a given alignment, ie increase the value to the next multiple of the alignment if it is not already aligned.
What is a concise way to do this in C++?
eg
int x;
int alignment;
int y = ???; // align x to alignment
alignof and alignas The alignas type specifier is a portable, C++ standard way to specify custom alignment of variables and user defined types. The alignof operator is likewise a standard, portable way to obtain the alignment of a specified type or variable.
64-bit aligned is 8 bytes aligned). A memory access is said to be aligned when the data being accessed is n bytes long and the datum address is n-byte aligned. When a memory access is not aligned, it is said to be misaligned. Note that by definition byte memory accesses are always aligned.
A 1-byte variable (typically a char in C/C++) is always aligned. A 2-byte variable (typically a short in C/C++) in order to be aligned must lie at an address divisible by 2. A 4-byte variable (typically an int in C/C++) must lie at an address divisible by 4 and so on.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With